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;
}
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.
source
share