我有一个班级名单A
like
class A {
private Integer keyA;
private Integer keyB;
private String text;
}
我要转让aList
嵌套Map
映射于keyA
and keyB
所以我创建了下面的代码。
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
对于这种行为。
看来你只需要一个级联groupingBy
:
Map<Integer, Map<Integer,List<A>>> aMappedByKeyAAndKeyB = aList.stream()
.collect(Collectors.groupingBy(A::getKeyA,
Collectors.groupingBy(A::getKeyB)));
本文内容由网友自发贡献,版权归原作者所有,本站不承担相应法律责任。如您发现有涉嫌抄袭侵权的内容,请联系:hwhale#tublm.com(使用前将#替换为@)