首页 > 解决方案 > 如何使用 Java 8 根据条件替换列表中的自定义对象?

问题描述

有两个自定义对象列表,Entity(id, name) - mainEntityList, otherEntityList我想遍历它们以将其中的项目替换为mainEntityListidotherEntityList匹配的项目。

前任

mainEntityList = [{1, "abc"},{2, "xyz"}]
otherEntityList = [{2, "value"}]

然后更换后我应该有

mainEntityList = [{1, "abc"},{2, "value"}]

它使用传统的循环方法,但使用 java 流的最佳解决方案是什么?谢谢!

标签: java-8java-stream

解决方案


从您将每个 Id 映射到 Entity 对象创建一个映射otherEntityList,然后List.replaceAll在映射键集包含您的 id 时使用检查mainEntityList

List<Entity> mainEntityList  = new ArrayList<>();
mainEntityList.add(new Entity(1, "abc"));
mainEntityList.add(new Entity(2, "xyz"));

List<Entity> otherEntityList = new ArrayList<>();
otherEntityList.add(new Entity(2, "value"));

Map<Integer,Entity> map = otherEntityList.stream().collect(Collectors.toMap(Entity::getId,Function.identity()));
mainEntityList.replaceAll(entity -> map.keySet().contains(entity.getId()) ? map.get(entity.getId()): entity);
System.out.println(mainEntityList);

推荐阅读