Pergunta

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())...?
Foi útil?

Solução

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

Outras dicas

Stream<Person> persons = groups.stream().flatMap(g -> g.getPersons().stream());

I guess you need flatMap:

Stream<Person> persons = groups.stream().flatMap(g -> g.getPersons().stream());
Licenciado em: CC-BY-SA com atribuição
Não afiliado a StackOverflow
scroll top