代码例子
//测试数据类
@Data
@Accessors(chain = true)
static class Test {
Integer id;
List<String> list;
}
List<Test> testList = new ArrayList<>();
testList.add(new Test().setId(1).setList(Stream.of("1a", "1b", "1c").collect(Collectors.toList())));
testList.add(new Test().setId(1).setList(Stream.of("1d", "1e").collect(Collectors.toList())));
testList.add(new Test().setId(2).setList(Stream.of("2a", "2b", "2f").collect(Collectors.toList())));
testList.add(new Test().setId(2).setList(Stream.of("2c", "2d", "2e").collect(Collectors.toList())));
testList.add(new Test().setId(3).setList(Stream.of("3x", "3y", "3z").collect(Collectors.toList())));
Map<Integer, List<String>> collect =
testList.stream()
.collect(Collectors.groupingBy(
Test::getId,
Collectors.collectingAndThen(
Collectors.mapping(Test::getList, Collectors.toList()),
i -> i.stream().flatMap(List::stream).collect(Collectors.toList())
)
));
System.out.println("collect = " + collect);
//运行结果 collect = {1=[1a, 1b, 1c, 1d, 1e], 2=[2a, 2b, 2f, 2c, 2d, 2e], 3=[3x, 3y, 3z]}
版权声明:本文为xw_725原创文章,遵循 CC 4.0 BY-SA 版权协议,转载请附上原文出处链接和本声明。