[英]How to convert List of Objects into Map<Object, Object> using Java 8 Lambdas
I have List of Objects say Car which Needs to be converted to Map. 我有对象列表说需要转换为地图的汽车。
Public Class Car {
private Integer carId;
private Integer companyId;
private Boolean isConvertible;
private String carName;
private String color;
private BigDecimal wheelBase;
private BigDecimal clearance;
}
I have another object which I want to treat as key of Map. 我有另一个对象,我想把它当作Map的关键。
public class Key<L, C, R> {
private L left;
private C center;
private R right;
}
I want to create a map from List of Car objects. 我想从List of Car对象创建一个地图。
List<Car> cars;
Map<Key, Car> -> This map contains Key object created from 3 field of Car object namely carId, companyId, isConvertible.
I am unable to figure out how to do this using Java 8 Lambda 我无法弄清楚如何使用Java 8 Lambda执行此操作
cars.stream.collect(Collectors.toMap(?, (c) -> c);
In above statement, in place of ?, I want to create object of Key class using values present in current car object. 在上面的语句中,代替?,我想使用当前car对象中存在的值创建Key类的对象。 How can I achieve this?
我怎样才能做到这一点?
You can do: 你可以做:
Function<Car, Key> mapper = car -> new Key(car.getId(),
car.getCompanyId(),
car.isConvertible());
cars.stream().collect(Collectors.toMap(mapper, Function.identity());
cars.stream().collect(Collectors.toMap(c->new Key(c.getId(),...), Function.identity());
You can also try this : 你也可以试试这个:
Map<Key, Car> carMapper = new HashMap<>();
carlist.forEach(car -> carMapper.put(new Key(car.getCarId(), car.getCompanyId(), car.getIsConvertible()), car));
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.