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/