How to convert a list into a map in Java 8 Map function in chain
•
Java
See the English answer > java 8 grouping using custom collector? 3
class Passenger { String type; String firstName; String lastName; //getter,setter public String getName() { return firstName + " " + lastName } }
Now I want to convert the passenger list into a map, where the key is "type" and the value is "name"
I try to achieve the following,
passengerList.stream().map(w -> w.getName()).collect(groupBy( getType() ));
But in After the map function, the passenger has been mapped to firstname, and the type is no longer available. I don't know how to do this
Solution
You must first group and then use the mapping to get a list of names for each type:
Map<String,List<String>> namesByType = passengerList.stream() .collect(Collectors.groupingBy(Passenger::getType,Collectors.mapping(Passenger::getName,Collectors.toList())));
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
二维码