Reputation: 329
I have a list of objects List<Car> cars
public class Car{
String make;
String model;
String year;
String price;
}
I want a succinct way of converting this list to a map Map<String, List<Car>>
using make as the key. I could write a function to do that but I was wondering if Lambdas or stream api in Java 8 provides an out of the box way to achieve this.
I have modified the question for a Map<String, List<Car>>
Upvotes: 0
Views: 91
Reputation: 3797
Yes its very well supported.
Do like this :
Map<String, List<Car>> youCarMap = yourCarList.stream().collect(
Collectors.groupingBy(Car::getMake,
Collectors.mapping(c->c, Collectors.toList())));
Upvotes: 4
Reputation: 56393
Map<String, List<Car>> result =
myList.stream()
.collect(Collectors.groupingBy(Car::getMake));
Upvotes: 1
Reputation: 2981
You can do it like so
cars.stream()
.collect(Collectors.toMap(
car -> car.make,
Function.identity()
)
Upvotes: 0