I want to iterate over a collection of collections. With Guava I would do this:
import static com.google.collections.Iterables.*;
class Group {
private Collection<Person> persons;
public Collection<Person> getPersons();
}
class Person {
private String name;
public String getName();
}
Collection<Group> groups = ...;
Iterable<Person> persons = concat(transform(groups, Group::getPersons()));
Iterable<String> names = transform(persons, Person::getName);
But how can I do the same thing with Java 8 streams?
groups.stream().map(Group::getPersons())...?
Using the concat() Method. The static method concat() combines two Streams logically by creating a lazily concatenated Stream whose elements are all the elements of the first Stream followed by all the elements of the second Stream.
One way to merge multiple lists is by using addAll() method of java. util. Collection class, which allows you to add the content of one List into another List. By using the addAll() method you can add contents from as many List as you want, it's the best way to combine multiple List.
Concatenate Objects of Same Class To concatenate Java objects, use either the cat function or the [] operators. Concatenating objects of the same Java class results in an array of objects of that class.
In Java 8 Streams, the flatMap() method applies operation as a mapper function and provides a stream of element values. It means that in each iteration of each element the map() method creates a separate new stream. By using the flattening mechanism, it merges all streams into a single resultant stream.
You can achieve this with flat mapping all elements of a stream into your stream.
Let me explain by this code:
groups.stream()
.flatMap(group -> group.getPersons().stream());
What you do here, is:
Stream<Collection<Group>>
.Stream<Person>
, from a Group
, back into your original stream, which is of type Stream<Person>
.Now after the flatMap()
, you can do whatever you want with the obtained Stream<Person>
.
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