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;
}