有两个自定义对象列表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);