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>
?
There is nothing like LINQ for Java. Now with Java 8 we are introduced to the Stream API, this is a similar kind of thing when dealing with collections, but it is not quite the same as Linq.
A stream consists of source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described. Stream is used to compute elements as per the pipelined methods without altering the original value of the object.
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
.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With