Home > database >  I am getting an error, java heap space error while i am trying to itirate in and add to a ArrayList
I am getting an error, java heap space error while i am trying to itirate in and add to a ArrayList

Time:03-24

public ArrayList<Product> search(Department dept){
    //Product target = null;
    ArrayList<Product> list = new ArrayList<Product>();
    boolean count=false;
    while(!count) {
        for(int index=0;index<data.size();index  ) {
            Product pd=data.get(index);
            if(pd.getDepartment().equals(dept)) {
                list.add(pd);
                count=false;
                break;
            }
            count=true;
        }
    
    }
    return list;
}

Here Department is an Enum class and I want to search for all the Object (Products) with a particular enum and add them to a new array list and return that.

CodePudding user response:

You need only one loop:

    public List<Product> search(Department dept) {
        List<Product> list = new ArrayList<Product>();
        
        for (int index = 0; index < data.size(); index  ) {
            Product pd = data.get(index);
            if (pd.getDepartment().equals(dept)) {
                list.add(pd);
            }
        }

        return list;
    }

The same implementation via Stream:

    public List<Product> search(Department dept) {
        return data.stream().filter(product -> product.getDepartment().equals(dept)).collect(Collectors.toList());
    }

CodePudding user response:

Use foreach instead

    public ArrayList<Product> search(Department dept){

        ArrayList<Product> response = new ArrayList<Product>();

        for (Product pd: data) {
            if(pd.getDepartment().equals(dept)){
                response.add(pd);
            }
        }

        return response;
    }
  • Related