Ami*_*toj 8 java lambda java-8 java-stream collectors
我有一个类型列表,List<A>
并且通过map操作获得了List<B>
所有A元素合并到一个列表中的类型的集合列表。
List<A> listofA = [A1, A2, A3, A4, A5, ...]
List<B> listofB = listofA.stream()
.map(a -> repo.getListofB(a))
.flatMap(Collection::stream)
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
没有平面图
List<List<B>> listOflistofB = listofA.stream()
.map(a -> repo.getListofB(a))
.collect(Collectors.toList());
Run Code Online (Sandbox Code Playgroud)
我想将结果收集为类型图,Map<A, List<B>>
到目前为止,我尝试使用各种Collectors.toMap
或Collectors.groupingBy
选项,但无法获得所需的结果。
您可以将toMap
收集器与有限方法引用一起使用以获取所需的内容。还要注意,该解决方案假定您在源容器中没有重复的A实例。如果该前提成立,则该解决方案将为您提供所需的结果。这是它的外观。
Map<A, Collection<B>> resultMap = listofA.stream()
.collect(Collectors.toMap(Function.identity(), repo::getListofB);
Run Code Online (Sandbox Code Playgroud)
如果您有重复的A元素,那么除了上面给出的内容之外,还必须使用此合并功能。合并功能处理键冲突(如果有)。
Map<A, Collection<B>> resultMap = listofA.stream()
.collect(Collectors.toMap(Function.identity(), repo::getListofB,
(a, b) -> {
a.addAll(b);
return a;
}));
Run Code Online (Sandbox Code Playgroud)
这是更简洁的Java9方法,它使用flatMapping
收集器来处理重复的A元素。
Map<A, List<B>> aToBmap = listofA.stream()
.collect(Collectors.groupingBy(Function.identity(),
Collectors.flatMapping(a -> getListofB(a).stream(),
Collectors.toList())));
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
155 次 |
最近记录: |