Home > Back-end >  Is there a way to reduce the amount of loops in this class?
Is there a way to reduce the amount of loops in this class?

Time:03-27

Recently started with Java. I have a class where several methods loop over an Arraylist, I am wondering if there would be a way to reduce the amount of loops as they only do one check really. Some sort of way to implement a function and pass predicate? I discovered Lambdas yesterday, but not sure it would be applicable here.

public class Stock {
    private ArrayList<Products> _productList;
    public Stock(){}

    public Boolean addProduct(Products product){
        return _productList.contains(product) && _productList.add(product);
    }

    public int obtainPos(int code){
        for(int i=0; i < _productList.size(); i  )
            if(_productList.get(i).getCode() == code)
                return i;
        return -1;
    }

    public void removeProduct(int code){
        int pos = obtainPos(code);
        if(pos >=0)
            _productList.remove(pos);
        else
            System.out.println("Error - Product not found.");
    }

    public int productAmount(){ return _productList.size(); }

    public int amountType(String type){
        int i = 0;
        for(Products pr : _productList)
            if(pr.getClass().getSimpleName().equals(type))
                i  ;
        return i;
    }

    @Override
    public String toString(){
        StringBuilder sb = new StringBuilder();
        for(Products pr : _productList)
            sb.append(pr.getName()).append(" \n");
        return sb.toString();
    }

    public void itemsToRemove(String reason){
        StringBuilder st = new StringBuilder();
        for(Products pr : _productList)
            st.append(pr.getName()).append(" - ").append(pr.withdraw(reason)).append("\n");

        System.out.println(st.toString());
    }
}

Thanks!

CodePudding user response:

You could have something like an if statement inside your desired single loop that decides between the actions you'd like to take, for example:

public void loopClass(int decision) {
for(Products pr : _productList) {
if (decision == choice1) {
//do something
}

if (decision == choice2) {
//do something else
}

//etc etc
}

}

Looking at your code I don't see anything wrong with the way you have loops set up though. It seems pretty concise and clear the way you have it set up now. I would recommend leaving it as is.

CodePudding user response:

You could use a HashMap<Integer,Products> instead of an ArrayList<Products>. That would allow you to eliminate obtainPos and reduce addProduct and removeProduct to O(1) operations.

  • Related