How to map this in Java 8 using thread API?

So, I have one List<Person>. and everyone Personhas List<String>, which is a list of phone numbers that this 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 Map<String, Person>where the key is the phone number that belongs to the person, and the value is the actual person.

That’s better to explain. 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 called this method. That would give me the followingMap<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 API stream, since I already know how to do this using loops for, etc.

+4
source share
3

persons PhoneNumberAndPerson ( Tuple Pair)

:

. PhoneNumberAndPerson . flatMap, . Map , PhoneNumberAndPerson Person PhoneNumberAndPerson.

persons.stream()
    .flatMap(person -> person.getPhoneNumbers().stream().map(phoneNumber -> new PhoneNumberAndPerson(phoneNumber, person)))
    .collect(Collectors.toMap(pp -> pp.getPhoneNumber(), pp -> pp.getPerson()));
+5

:

Map<String, Person> result = list.stream().collect(HashMap::new,
     (map, p) -> p.getPhoneNumbers().forEach(phone -> map.put(phone, p)), HashMap::putAll);
+4

- :

    Map<String, String> map = new HashMap<>();
    list.stream().forEach(p -> p.getPhoneNumbers().forEach(n -> map.put(n, p.getName())));

Edit: as suggested by Simon, you can use the collect method, but it can be tricky if you want to create a map using the class you provided with a simpler class (without using List, but just a simple String in to save the number) you can just call the code below which returns the map

list.stream().collect(Collectors.toMap(Person::getPhoneNumber, Person::getName));
+2
source

All Articles