Skip to content

Java Stream equivalent of LINQ SelectMany()

What’s the Java 8 Stream equivalent of LINQ’s 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).

Is there a Java equivalent for a Map<String, List<Tag>> that would yield a Stream<Tag>?



You’re looking to flatMap all the values contained in the map:

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.

User contributions licensed under: CC BY-SA
2 People found this is helpful