gpt4 book ai didi

Java8 : Map list of objects by key

转载 作者:行者123 更新时间:2023-12-02 12:49:44 25 4
gpt4 key购买 nike

Map<A, List<B>> xFunction() {    
Map<A, List<B>> mapList = new HashMap<>();
List<A> aList = x.getAList();
for (A a : aList) {
List<B> bList = getBList(a.getId());
mapList.put(a, bList);
}
return mapList;
}

如何在 java 8 中使用收集和分组或映射来转换它?

我尝试使用类似的东西:

x.getAList
.stream()
.map(a -> getBList(a.getId)) //return a list of B
.collect(Collectors.groupingBy (...) )

干杯

最佳答案

您需要Collectors.toMap:

Map<A, List<B>> map =
x.getAList()
.stream()
.collect(Collectors.toMap (Function.identity(), a -> getBList(a.getId())));

关于Java8 : Map list of objects by key,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/46641259/

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