sophist_pt
sophist_pt

Reputation: 329

Converting a list of objects in java to a map of String key to List<objects> using one of its field as the key

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>>

Upvotes: 0

Views: 91

Answers (3)

Shanu Gupta
Shanu Gupta

Reputation: 3797

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())));

Upvotes: 4

Ousmane D.
Ousmane D.

Reputation: 56393

Map<String, List<Car>> result = 
          myList.stream()
                .collect(Collectors.groupingBy(Car::getMake));

Upvotes: 1

Stefan Zhelyazkov
Stefan Zhelyazkov

Reputation: 2981

You can do it like so

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

Upvotes: 0

Related Questions