java-8 - 如何使用 Java 8 根据条件替换列表中的自定义对象?
问题描述
有两个自定义对象列表,Entity(id, name) - mainEntityList, otherEntityList
我想遍历它们以将其中的项目替换为mainEntityList
idotherEntityList
匹配的项目。
前任
mainEntityList = [{1, "abc"},{2, "xyz"}]
otherEntityList = [{2, "value"}]
然后更换后我应该有
mainEntityList = [{1, "abc"},{2, "value"}]
它使用传统的循环方法,但使用 java 流的最佳解决方案是什么?谢谢!
解决方案
从您将每个 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);
推荐阅读
- excel - 防止特定列添加新行
- firebase - 功能无法在本地工作的 Firebase 托管
- sockets - 可以依靠 Clamd 来解压 RFC-822 格式的 .eml 文件吗?它似乎做到了
- javascript - Nodejs 保护特定用户的资源
- swift - 将 *generic* 协议桥接到 Objective-C 的解决方法?
- reactjs - 如何折叠下拉列表 React Native
- swift - 无法引用 Firestore 文档路径
- wordpress - 有可能用数学运算做一个 WP_Query 吗?
- javascript - 在 React 中获取元素 onClick 的背景颜色
- java - SharedPreferences getString 返回 null