Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Concatenate Collections with Java 8

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())...?
like image 995
Philipp Jardas Avatar asked Apr 06 '14 11:04

Philipp Jardas


People also ask

How do you concatenate a collection in Java?

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.

How do I combine multiple lists into one in Java?

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.

How do you concatenate objects in Java?

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.

What is a flatMap in Java 8?

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.


1 Answers

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:

  1. Obtain a Stream<Collection<Group>>.
  2. Then flat map every obtained 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>.

like image 68
skiwi Avatar answered Sep 27 '22 23:09

skiwi