Reputation: 33
I'm trying to learn more about the streams in java and I was wondering how can I use the toMap to change a List of items into a map that has a property of those items as key and a sublist of the same List as value. For example if I have an class:
public class Car {
private String color;
private String model;
// getters and setters
}
if I have: List<Car> carList;
, how can I get a Map<String, List<Car>>
where the entries will be something like:
"BLUE" : {car1, car3, car7},
"RED" : {car2, car5, car6, car8},
"WHITE" : {car4, car9}
I understand that in order to get it I can run something like the following statement however I don't understand what the second parameter should be:
Map<String, List<Car>> carsMap = list.stream()
.collect(Collectors.toMap(Car::getColor, ?));
would someone please help me get this correct?
Upvotes: 3
Views: 1082
Reputation: 18430
toMap()
normally used to collect into a Map
that contains a single value by key.
You can use groupingBy
for group by Color, groupingBy
is better choice to collect into a Map
that contains multiple values by key.
Map<String, List<Car>> carsMap = list.stream()
.collect(Collectors.groupingBy(Car::getColor));
Upvotes: 4
Reputation: 56423
Sounds more of groupingBy
job than a toMap
:
list.stream().collect(Collectors.groupingBy(Car::getColor));
Upvotes: 3