我有一个 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
来实现这种行为。
最佳答案
似乎你只需要一个级联的groupingBy
:
Map<Integer, Map<Integer,List<A>>> aMappedByKeyAAndKeyB = aList.stream()
.collect(Collectors.groupingBy(A::getKeyA,
Collectors.groupingBy(A::getKeyB)));
关于Java 8 列表到嵌套映射,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/33644751/