Java8:按键映射对象列表

emo*_*ssi 2 java java-8 java-stream

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;
}
Run Code Online (Sandbox Code Playgroud)

如何在java 8中使用collect和grouping或映射转换它?

我试着用这样的东西:

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

干杯

Era*_*ran 6

你需要Collectors.toMap:

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

  • 你比我快30秒. (3认同)