Java8:按键映射对象列表

Java8:按键映射对象列表,java,java-8,java-stream,Java,Java 8,Java Stream,干杯您需要收藏家。toMap: x.getAList .stream() .map(a -> getBList(a.getId)) //return a list of B .collect(Collectors.groupingBy (...) ) 地图= x、 getAList() .stream() .collect(Collectors.toMap(Function.identity(),a->getBList(a.getId())); @Eran是第一个,但要复制行为,您应该使

干杯

您需要
收藏家。toMap

x.getAList
.stream()
.map(a -> getBList(a.getId)) //return a list of B
.collect(Collectors.groupingBy (...) )
地图=
x、 getAList()
.stream()
.collect(Collectors.toMap(Function.identity(),a->getBList(a.getId()));

@Eran是第一个,但要复制行为,您应该使用
toMap
收集器和
mergeFunction
,通过
a.getId()
对重复项执行操作,因为默认情况下,对于具有相同键的条目,Java将抛出
IllegalStateException

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

你比我快30秒。
Map<A, List<B>> map =
    x.getAList()
     .stream()
     .collect(Collectors.toMap (Function.identity(), a -> getBList(a.getId())));
x.getAList()
    .stream()
    .collect(Collectors.toMap(Function.identity(), a -> getBList(a.getId())), (u, u2) -> u2);