vaibhavvc1092 vaibhavvc1092 - 1 year ago 65
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, (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 Source

You can do:

Function<Car, Key> mapper = car -> new Key(car.getId(), 
                                           car.isConvertible());, Function.identity());
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download