Is there a way to reduce the amount of loops in this class?

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!



Comments

Popular posts from this blog

Today Walkin 14th-Sept

Spring Elasticsearch Operations

Hibernate Search - Elasticsearch with JSON manipulation