[英]Converting a list of objects in java to a map of String key to List<objects> using one of its field as the key
I have a list of objects List<Car> cars
我有一个对象
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. 我想以简洁的方式将此列表转换为使用make作为键的
Map<String, List<Car>>
。 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. 我可以编写一个函数来做到这一点,但是我想知道Java 8中的Lambdas或流api是否提供了一种开箱即用的方式来实现这一点。
I have modified the question for a Map<String, List<Car>>
我已经修改了
Map<String, List<Car>>
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())));
Map<String, List<Car>> result =
myList.stream()
.collect(Collectors.groupingBy(Car::getMake));
You can do it like so 你可以这样做
cars.stream()
.collect(Collectors.toMap(
car -> car.make,
Function.identity()
)
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.