简体   繁体   中英

Copying specified objects from one ArrayList to another

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?

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;

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM