使用Collectors.toMap或groupingBy收集Map中地图操作的结果

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.toMapCollectors.groupingBy选项,但无法获得所需的结果。

Rav*_*ala 8

您可以将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)

  • 嘿,很高兴您添加了如何处理重复项!我在此添加一个答案,我会接受的,因为我认为它对您的内容有好处,加油! (2认同)
  • 是的,您的评论很有帮助。接得好 ! (2认同)