如何用Java 8 Streams实现嵌套循环的Collectors.groupingBy分组
Java 8 Streams 实现分组逻辑
原循环逻辑回顾
你需要将Collection<Object>中的每个对象,根据其ids列表中的每个元素,拼接成StringUtils.joinAll("|", obj.getAtt(), id)作为键,将对象分组到Map<String, List<Object>>中。原嵌套循环的逻辑是遍历每个对象和其下的id,手动维护Map的分组关系。
Streams 实现代码
Map<String, List<Object>> objMap = listOfObjects.stream() .flatMap(obj -> obj.getIds().stream() .map(id -> new AbstractMap.SimpleEntry<>( StringUtils.joinAll("|", obj.getAtt(), id), obj )) ) .collect(Collectors.groupingBy( Map.Entry::getKey, Collectors.mapping(Map.Entry::getValue, Collectors.toList()) ));
代码说明
- flatMap:将每个对象展开为多个
(键, 对象)的条目流,每个id对应一个条目,等价于原嵌套循环中遍历id的逻辑。 - AbstractMap.SimpleEntry:临时存储拼接后的键和对应的对象,为后续分组提供清晰的键值映射。
- Collectors.groupingBy:按条目键分组,并用
Collectors.mapping将条目值(原对象)收集到List中,替代原循环中手动判断Map是否存在键、创建列表的冗余逻辑。
如果需要指定Map的具体实现(比如原代码中的HashMap),可以重载groupingBy方法:
Map<String, List<Object>> objMap = listOfObjects.stream() .flatMap(obj -> obj.getIds().stream() .map(id -> new AbstractMap.SimpleEntry<>( StringUtils.joinAll("|", obj.getAtt(), id), obj )) ) .collect(Collectors.groupingBy( Map.Entry::getKey, HashMap::new, Collectors.mapping(Map.Entry::getValue, Collectors.toList()) ));
内容的提问来源于stack exchange,提问作者Prashant Chindhade
相关产品推荐
相关产品推荐

