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.
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()));
                        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