How to convert a List of objects to Map <Object, Object> using Java 8 Lambdas

I have a list of objects: a car that needs to be converted to a 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 that I want to consider as a map key.

  public class Key<L, C, R> { private L left; private C center; private R right; } 

I want to create a map from the "Car List" objects.

 List<Car> cars; Map<Key, Car> -> This map contains Key object created from 3 field of Car object namely carId, companyId, isConvertible. 

I can't figure out how to do this using Java 8 Lambda

 cars.stream.collect(Collectors.toMap(?, (c) -> c); 

In the above expression, instead of?, I want to create an object of class Key, using the values ​​present in the current object of the car. How can I achieve this?

+8
java dictionary list lambda java-8
source share
3 answers

You can do:

 Function<Car, Key> mapper = car -> new Key(car.getId(), car.getCompanyId(), car.isConvertible()); cars.stream().collect(Collectors.toMap(mapper, Function.identity()); 
+10
source share
 cars.stream().collect(Collectors.toMap(c->new Key(c.getId(),...), Function.identity()); 
0
source share

You can also try the following:

  Map<Key, Car> carMapper = new HashMap<>(); carlist.forEach(car -> carMapper.put(new Key(car.getCarId(), car.getCompanyId(), car.getIsConvertible()), car)); 
0
source share

All Articles