【发布时间】:2020-09-15 10:43:26
【问题描述】:
我有两个列表:
List<Product> productsListOne;
List<Products> productsListTwo;
第一个列表包含所有产品,第二个列表包含一些产品(其中一些产品具有相同的 id),但类别不同。
我的目标是查找productsListOne 中是否有来自productsListTwo 的产品ID。任务的第二部分是,如果找到这样的产品,它需要将productsListOne 产品类别从productsListTwo 的产品更改为相同的类别。
我用for each 循环尝试了一些解决方案,但没有取得更大的成功。
for (Product secondListProduct: productsListTwo) {
for (Product firstListProduct: productsListOne) {
if (productsListTwo.get(productsListTwo.indexOf(secondListProduct)).getId() == firstListProduct.get(firstListProduct.indexOf(firstListProduct)).getId()){
firstListProduct.get(firstListProduct.indexOf(firstListProduct)).setCategory(productsListTwo.get(productsListTwo.indexOf(secondListProduct)).getCategory());
}
}
}
第二次尝试使用流:
for (Product p:secondListProduct) {
if(firstListProduct.stream().filter(o -> o.getId() == p.getId()).findFirst().isPresent()){
System.out.println("found one");
}
}
【问题讨论】:
-
向我们展示您迄今为止的尝试?还有一个输入输出示例
-
这里其实不需要
indexOf,你可以像if (firstListProduct.getId() == secondListProduct.getId()){firstListProduct.setCategory(secondListProduct.getCategory());}一样操作
标签: java arraylist collections