Java 8:将列表与流 API 合并

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/23112874/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-13 20:46:44  来源:igfitidea点击:

Java 8: merge lists with stream API

javalistjava-8java-stream

提问by mat_boy

I have the following situation

我有以下情况

Map<Key, ListContainer> map; 

public class ListContainer{
  List<AClass> lst;
}

I have to merge all the lists lstfrom the ListContainerobjects from a Mapmap.

我已经合并所有列表lstListContainer从对象Map地图。

public static void main(String args[]){
   List<AClass> alltheObjectsAClass = map.values().stream(). // continue....    
}

Any idea how, using Java 8 stream API?

知道如何使用 Java 8 流 API 吗?

采纳答案by Puce

I think flatMap()is what you're looking for.

我想flatMap()这就是你要找的。

For example:

例如:

 List<AClass> allTheObjects = map.values()
         .stream()
         .flatMap(listContainer -> listContainer.lst.stream())
         .collect(Collectors.toList());

回答by Skywalker

Alternative: Stream.concat()

替代方案:Stream.concat()

Stream.concat(map.values().stream(), listContainer.lst.stream())
                             .collect(Collectors.toList()

回答by Konzern

In Java 8 we can use stream List1.stream().collect(Collectors.toList()).addAll(List2); Another option List1.addAll(List2)

在 Java 8 中,我们可以使用流 List1.stream().collect(Collectors.toList()).addAll(List2); 另一个选项 List1.addAll(List2)