如何使用Java Stream API按TestC的e、f组合分组TestA列表?
问题描述
现有类结构如下:
TestA { int a; int b; TestC testC; } TestC { int d; String e; String f; }
拥有一个List<TestA>对象列表,需要使用Java Stream API将该列表按照TestC对象中的e、f变量组合进行分组,最终得到一个Map<String, List<TestA>>,其中键为e与f的字符串组合(格式如"e值+f值"),值为对应分组后的TestA列表。
示例数据代码:
TestA x1 = new TestA(); x1.setTestC(new TestC(d1, e1, f1)); TestA x2 = new TestA(); x2.setTestC(new TestC(d1, e1, f1)); TestA x3 = new TestA(); x3.setTestC(new TestC(d2, e2, f2)); List<TestA> l1 = new ArrayList<>(); l1.add(x1); l1.add(x2); l1.add(x3);
期望分组结果:键为"e1+f1"对应包含x1、x2的列表,键为"e2+f2"对应包含x3的列表。
实现方案
可以直接使用Stream的Collectors.groupingBy()方法,通过自定义分组键的生成逻辑来实现:
Map<String, List<TestA>> groupedMap = l1.stream() .collect(Collectors.groupingBy(testA -> { TestC testC = testA.getTestC(); return testC.getE() + "+" + testC.getF(); }));
关键点说明
Collectors.groupingBy()接收一个函数,用于提取每个元素的分组键;- 这里通过
testA.getTestC()获取关联的TestC对象,再拼接e和f作为分组键; - 如果业务中存在
testC或e/f为null的场景,建议添加非空判断避免空指针异常,示例如下:
Map<String, List<TestA>> groupedMap = l1.stream() .filter(testA -> testA.getTestC() != null && testA.getTestC().getE() != null && testA.getTestC().getF() != null) .collect(Collectors.groupingBy(testA -> { TestC testC = testA.getTestC(); return testC.getE() + "+" + testC.getF(); }));
内容的提问来源于stack exchange,提问作者user2755407
相关产品推荐
相关产品推荐

