我有一个类别为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
。