Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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>?

like image 383
Robert Fraser Avatar asked Mar 14 '16 15:03

Robert Fraser


People also ask

Does Java have an equivalent to LINQ?

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.

What is stream method in Java?

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.


1 Answers

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.

like image 114
Tunaki Avatar answered Oct 20 '22 11:10

Tunaki