Java 8列表到嵌套映射
我有一个类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
来进行这种行为
# 1 楼答案
似乎您只需要一个级联的
groupingBy
: