【发布时间】:2015-04-04 03:39:42
【问题描述】:
我目前有一个 ArrayList 保存“产品”对象,每个对象中都包含一个字符串、整数和双精度值。 我希望能够使用参数搜索对象,找出与搜索参数匹配的 ID(整数值)并将该对象复制到另一个 ArrayList 中。是否可以通过 Iterator 来做到这一点,还是有更简单的方法来做到这一点?
【问题讨论】:
我目前有一个 ArrayList 保存“产品”对象,每个对象中都包含一个字符串、整数和双精度值。 我希望能够使用参数搜索对象,找出与搜索参数匹配的 ID(整数值)并将该对象复制到另一个 ArrayList 中。是否可以通过 Iterator 来做到这一点,还是有更简单的方法来做到这一点?
【问题讨论】:
简单的方法是使用 Java 8 流:
List<Product> filtered =
prods.stream().filter(p -> p.getId() == targetId).collect(toList());
假设import static java.util.stream.Collectors.toList;
【讨论】:
Java 少 8 版的简单直接解决方案:
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);
}
}
【讨论】: