2

I have a class Person having a set of Objects Contacts. I want to get a stream of Contacts from the stream of Persons.

public class Persons{
     private Set<Contact> contacts;
}

persons.stream().map(Person::getContacts);

gives me Stream<Set<Contact>> rather a Stream<Contact>

Any suggestion or help would be appreciated as I am quite new to Java 8 and Streams.

Flown
  • 11,480
  • 3
  • 45
  • 62
Sneha
  • 317
  • 4
  • 15

2 Answers2

1

You can achieve this by using Stream#flatMap instead of Stream#map. The JavaDoc shows an example of flattening a list of lines from a file to a list of words within each line. You can adapt the same technique to your domain model of Person and Contact.

Chris Nauroth
  • 9,614
  • 1
  • 35
  • 39
1

You may try this:

Stream<Contact> contacts = persons.stream().flatMap(p -> p.getContacts().stream());

or that:

Stream<Contact> contacts = persons.stream().map(Person::getContacts).flatMap(Set::stream);

Check this excellent thread so that you may understand the difference between map and flatMap.

Community
  • 1
  • 1
Lachezar Balev
  • 11,498
  • 9
  • 49
  • 72