【发布时间】:2016-02-12 04:50:38
【问题描述】:
我有一个 A 类的列表
class A {
private Integer keyA;
private Integer keyB;
private String text;
}
我想将aList 转移到由keyA 和keyB 映射的嵌套Map
所以我创建了下面的代码。
Map<Integer, Map<Integer,List<A>>> aMappedByKeyAAndKeyB = aList.stream()
.collect(Collectors.collectingAndThen(Collectors.groupingBy(A::getKeyA), result -> {
Map<Integer, Map<Integer, List<A>>> nestedMap = new HashMap<Integer, Map<Integer, List<A>>>();
result.entrySet().stream().forEach(e -> {nestedMap.put(e.getKey(), e.getValue().stream().collect(Collectors.groupingBy(A::getKeyB)));});
return nestedMap;}));
但我不喜欢这段代码。
我认为如果我使用flatMap,我可以编写比这更好的代码。
但我不知道如何使用 flatMap 来处理这种行为。
【问题讨论】:
标签: java java-8 java-stream collectors