gpt4 book ai didi

Java 8 列表到嵌套映射

转载 作者:塔克拉玛干 更新时间:2023-11-03 03:12:55 24 4
gpt4 key购买 nike

我有一个 A 类的列表

class A {
private Integer keyA;
private Integer keyB;
private String text;
}

我想将 aList 传输到由 keyAkeyB 映射的嵌套 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/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com