我有一个类A
的列表,如
class A {
private Integer keyA;
private Integer keyB;
private String text;
}
我想将aList
转移到由Map
和keyA
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
来解决这种问题。
答案 0 :(得分:14)
似乎您只需要级联groupingBy
:
Map<Integer, Map<Integer,List<A>>> aMappedByKeyAAndKeyB = aList.stream()
.collect(Collectors.groupingBy(A::getKeyA,
Collectors.groupingBy(A::getKeyB)));