[英]Converting a list of objects in java to a map of String key to List<objects> using one of its field as the key
我有一個對象List<Car> cars
public class Car{
String make;
String model;
String year;
String price;
}
我想以簡潔的方式將此列表轉換為使用make作為鍵的Map<String, List<Car>>
。 我可以編寫一個函數來做到這一點,但是我想知道Java 8中的Lambdas或流api是否提供了一種開箱即用的方式來實現這一點。
我已經修改了Map<String, List<Car>>
是的,它得到了很好的支持。
這樣做:
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));
你可以這樣做
cars.stream()
.collect(Collectors.toMap(
car -> car.make,
Function.identity()
)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.