Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 718
vaibhavvc1092 Avatar asked Aug 18 '15 10:08

vaibhavvc1092


People also ask

Can we convert List to Map in Java?

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.

Can we convert object to Map in Java?

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.


1 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());
like image 77
Konstantin Yovkov Avatar answered Oct 20 '22 04:10

Konstantin Yovkov