如何用Java Lambda提取属性并按value分组合并count构建列表?
解决Java Lambda分组累加嵌套列表的问题
嘿,我来帮你搞定这个Lambda处理的问题!你要做的就是把嵌套列表里的项按value分组,然后累加对应的count,对吧?之前分组没成功大概率是没先把嵌套列表扁平化,我给你一步步拆解:
第一步:定义对应的实体类
首先我们需要用Java类来映射你的JSON结构,用Java 16+的record会非常简洁(如果是旧版本,换成带getter的普通POJO类就行):
// 外层数据类 record OuterItem(int code, List<NestedItem> nestedList) {} // 嵌套的数据类 record NestedItem(String value, int count) {} // 最终要输出的结果类 record ResultItem(String value, int count) {}
第二步:用Lambda流处理数据
核心逻辑就是先扁平化嵌套列表,再分组累加,最后转成目标列表,代码如下:
// 模拟你提供的原始列表 List<OuterItem> originalList = List.of( new OuterItem(1, List.of(new NestedItem("A", 1))), new OuterItem(2, List.of(new NestedItem("A", 1))), new OuterItem(3, List.of(new NestedItem("A", 1))), new OuterItem(4, List.of(new NestedItem("B", 1))), new OuterItem(5, List.of(new NestedItem("B", 1))) ); List<ResultItem> resultList = originalList.stream() // 1. 扁平化:把每个外层对象里的nestedList拆成单个NestedItem流 .flatMap(outer -> outer.nestedList().stream()) // 2. 分组并累加:按value分组,对每组的count求和 .collect(Collectors.groupingBy( NestedItem::value, Collectors.summingInt(NestedItem::count) )) // 3. 转换为目标列表:把分组后的Map键值对转成ResultItem .entrySet().stream() .map(entry -> new ResultItem(entry.getKey(), entry.getValue())) .toList(); // Java 16+用toList(),旧版本用Collectors.toList() // 打印结果验证 resultList.forEach(System.out::println);
为什么之前分组没成功?
你可能直接对OuterItem进行分组了,但每个OuterItem的nestedList是一个集合,必须先用flatMap把所有嵌套的NestedItem都提取到同一个流里,之后再按value分组累加才会得到正确的结果~
内容的提问来源于stack exchange,提问作者Lucas
相关产品推荐
相关产品推荐

