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

对着背影说爱祢 提交于 2019-12-05 14:35:19
Simon

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

Without additional class and pre-creating map:

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

Without creating other classes i'd go for something like this:

    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 that you provided, with a simpler class ( without using List but just a plain String in order to store the number) you can simply call the code below that returns a Map

list.stream().collect(Collectors.toMap(Person::getPhoneNumber, Person::getName));
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!