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?
With Java 8, you can convert a List to Map in one line using the stream() and Collectors. toMap() utility methods. The Collectors. toMap() method collects a stream as a Map and uses its arguments to decide what key/value to use.
In Java 8, we have the ability to convert an object to another type using a map() method of Stream object with a lambda expression. The map() method is an intermediate operation in a stream object, so we need a terminal method to complete the stream.
You can do:
Function<Car, Key> mapper = car -> new Key(car.getId(),
car.getCompanyId(),
car.isConvertible());
cars.stream().collect(Collectors.toMap(mapper, Function.identity());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With