0

I have a list of objects List<Car> cars

public class Car{
  String make;
  String model;
  String year;
  String price;
}

I want a succinct way of converting this list to a map Map<String, List<Car>> using make as the key. I could write a function to do that but I was wondering if Lambdas or stream api in Java 8 provides an out of the box way to achieve this.

I have modified the question for a Map<String, List<Car>>

3

3 Answers 3

4

Yes its very well supported.

Do like this :

Map<String, List<Car>> youCarMap = yourCarList.stream().collect(
                Collectors.groupingBy(Car::getMake,
                    Collectors.mapping(c->c, Collectors.toList())));
Sign up to request clarification or add additional context in comments.

1 Comment

Slight modification to the question. I actually also want to prepare a Map<String, List<Car>> makeToCars. How can I achieve this? @Shanu Gupta
1
Map<String, List<Car>> result = 
          myList.stream()
                .collect(Collectors.groupingBy(Car::getMake));

Comments

0

You can do it like so

cars.stream()
   .collect(Collectors.toMap(
      car -> car.make,
      Function.identity()
   )

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.