Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I map this in Java 8 using the stream API?

Ok, so I have a List<Person>. and each Person has a List<String> that is a list of phone numbers that that person owns.

So this is the basic structure:

public class Person {

    private String name;
    private List<String> phoneNumbers;

    // constructors and accessor methods

}

I would like to create a Map<String, Person> where the key is each phone number that the person owns, and the value is the actual person.

So to explain better. If I had this List<Person>:

Person bob = new Person("Bob");
bob.getPhoneNumbers().add("555-1738");
bob.getPhoneNumbers().add("555-1218");

Person john = new Person("John");
john.getPhoneNumbers().add("518-3718");
john.getPhoneNumbers().add("518-3115");
john.getPhoneNumbers().add("519-1987");

List<Person> list = new ArrayList<>();
list.add(bob);
list.add(john);

and I invoked this method. It would give me the following Map<String, Person>

Map<String, Person> map = new HashMap<>();
map.put("555-1738", bob);
map.put("555-1218", bob);

map.put("518-3718", john);
map.put("518-3115", john);
map.put("519-1987", john);

I would like to know how to achieve this using the stream API, as I already know how I would do it using for loops and such.

like image 941
Rodrigo Sasaki Avatar asked Dec 18 '22 17:12

Rodrigo Sasaki


1 Answers

If you have list of persons called persons and a class called PhoneNumberAndPerson (you could use a generic Tuple or Pair instead)

These are the steps:

For each person, take each phone number of that person. For each of those phone numbers, create a new instance of PhoneNumberAndPerson and add that to a list. Use flatMap to make one single list of all these smaller lists. To make a Map out of this list you supply one function to extract a key from a PhoneNumberAndPerson and another function to extract a Person from that same PhoneNumberAndPerson.

persons.stream()
    .flatMap(person -> person.getPhoneNumbers().stream().map(phoneNumber -> new PhoneNumberAndPerson(phoneNumber, person)))
    .collect(Collectors.toMap(pp -> pp.getPhoneNumber(), pp -> pp.getPerson()));
like image 192
Simon Avatar answered Dec 21 '22 11:12

Simon