vaibhavvc1092 vaibhavvc1092 - 11 days ago 4
Java Question

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.

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<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

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. How can I achieve this?

Answer

You can do:

Function<Car, Key> mapper = car -> new Key(car.getId(), 
                                           car.getCompanyId(), 
                                           car.isConvertible());
cars.stream().collect(Collectors.toMap(mapper, Function.identity());
Comments