[英]Java Stream equivalent of LINQ SelectMany()
What's the Java 8 Stream equivalent of LINQ's SelectMany ? 什么是Java 8 Stream相当于LINQ的SelectMany ?
For example, in C#, if I have Dictionary<string, List<Tag>> tags
that I want to turn into an IEnumerable<Tag>
(a flat enumerable of all the tags in the dictionary), I would do tags.SelectMany(kvp => kvp.Value)
. 例如,在C#中,如果我有
Dictionary<string, List<Tag>> tags
,我想转变为IEnumerable<Tag>
(字典中所有标签的可枚举),我会做tags.SelectMany(kvp => kvp.Value)
。
Is there a Java equivalent for a Map<String, List<Tag>>
that would yield a Stream<Tag>
? 是否存在可以产生
Stream<Tag>
的Map<String, List<Tag>>
的Java等价物?
You're looking to flatMap
all the values contained in the map: 您正在寻找
flatMap
映射中包含的所有值:
Map<String, List<Tag>> map = new HashMap<>();
Stream<Tag> stream = map.values().stream().flatMap(List::stream);
This code first retrieves all the values of the map as a Collection<List<Tag>>
with values()
, creates a Stream out of this collection with stream()
, and then flat maps each List<Tag>
into a Stream
with the method reference List::stream
. 此代码首先使用
values()
检索地图的所有值作为Collection<List<Tag>>
,使用stream()
从此集合中创建Stream,然后将每个List<Tag>
平面映射到Stream
中方法引用List::stream
。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.