Reputation: 31
I currently have an ArrayList holding "Product" objects which contain a string, integer and double within each object. I want to be able to search through the objects using a parameter, to pick out the ID (integer value) which matches the search parameter and to copy this object into another ArrayList. Is it possible to do this through an Iterator or is there an easier way of doing this?
Upvotes: 1
Views: 2049
Reputation: 5028
Simple stright forward solution for Java less them 8 version:
ArrayList<Product> arrOriginal = new ArrayList<Product>(); //with values of yours
ArrayList<Product> arrCopy = new ArrayList<Product>(); //empty
for (Product item : arrOriginal){
if (<some condition>){
arrCopy.add(item);
}
}
Upvotes: 1
Reputation: 457
ArrayList<Product> arrListOriginal = new ArrayList<Product>();
arrListOriginal.add(item1);
arrListOriginal.add(item2);
arrListOriginal.add(item3);
ArrayList<Product> arrListCopy = new ArrayList<Product>();
Product objProduct = new Product();
for (int index=0;index<arrListOriginal.size();index++){
objProduct = (Product) arrListOriginal.get(index);
if (<search condition with objProduct>){
arrListCopy.add(objProduct);
}
}
Upvotes: 0
Reputation: 200148
The easy way is using Java 8 streams:
List<Product> filtered =
prods.stream().filter(p -> p.getId() == targetId).collect(toList());
Assuming import static java.util.stream.Collectors.toList;
Upvotes: 2