I would like to write lastnamesByFirstname method.
In the people lists, there are bunch of people, and each person have two field the firstname and the second name. I would like to write a method which will turn back in the following way, key value would be the firstname, and the value list would be those name which firstnames are the same. I tried with groupingby wiht sorting buts somehow never worked.
* {
* "Mary" -> ["Smith", "Silver"]
* "Joe" -> ["Smith"]
* }
*/
static Map<String, List<String>> lastnamesByFirstname(List<Person> people){
}
my attempt look like this, but the type would be not matching with the return type.
var peopleStream= people.stream()
.collect(groupingBy(Person::getFirstName));
>Solution :
In the second parameter of groupingBy, you can transform List<Person> to List<String> using mapping:
var peopleStream = people.stream()
.collect(groupingBy(Person::getFirstName,
mapping(Person::getLastName, Collectors.toList())));