使用流基于另一个列表更新一个列表

阿布·鲁卡雅(Abu Ruqaiyah)

我想从传入列表中更新现有列表中的项目。

class Person{
  String id;
  String name;
  String age;
.
.
.
  @Override
  public boolean equals(Object object) {
    return ... ((Person) object).id.equals(this.id);
  }
}

当前列表较短:

ArrayList<Person> currentList = Arrays.asList(
   new Person("0", "A", 25),
   new Person("1", "B", 35)
);

收到的列表较大,例如

ArrayList<Person> updatedList = Arrays.asList(
       new Person("0", "X", 99),
       new Person("1", "Y", 100),
       new Person("2", "C", 2),
       new Person("3", "D", 3),
       new Person("4", "E", 5)
    );

包括当前列表中的项目(由其ID标识)。

我想用新列表中的相同项替换当前列表中的所有项。

因此,转换后,当前列表将是

{ Person(0, "X", 99), Person(1, "Y", 100) }

是否可以仅使用Stream处理。

Dakshinamurthy Karra

假设您希望currentList项被updatedList中的对象替换,则应该可以进行以下操作:

currentList.stream().map((p) -> {
            return updatedList.stream().filter(u -> p.equals(u)).findFirst().orElse(p);
        }).collect(Collectors.toList());

本文收集自互联网,转载请注明来源。

如有侵权,请联系 [email protected] 删除。

编辑于
0

我来说两句

0 条评论
登录 后参与评论

相关文章