如何根据使用Java 8的条件替换列表中的自定义对象?



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

交货

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

那么替换之后我应该有

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

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

从您的otherEntityList映射每个Id到实体对象,然后使用List.replaceAll检查映射键集是否包含您的mainEntityList中的Id:

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

最新更新