9

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?

3 Answers 3

11

You can do:

Function<Car, Key> mapper = car -> new Key(car.getId(), 
                                           car.getCompanyId(), 
                                           car.isConvertible());
cars.stream().collect(Collectors.toMap(mapper, Function.identity());
Sign up to request clarification or add additional context in comments.

Comments

0
cars.stream().collect(Collectors.toMap(c->new Key(c.getId(),...), Function.identity());

Comments

0

You can also try this :

    Map<Key, Car> carMapper = new HashMap<>();

    carlist.forEach(car -> carMapper.put(new Key(car.getCarId(), car.getCompanyId(), car.getIsConvertible()), car));

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.