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

sophist_pt
  • 329
  • 1
  • 8
  • 19
  • Well, you could use [How to convert List to Map](https://stackoverflow.com/questions/4138364/java-how-to-convert-list-to-map) or if you really want to look l334, you could use [Java 8 List into Map](https://stackoverflow.com/questions/20363719/java-8-listv-into-mapk-v) or you could try one of the many logs you can find through Google like [Java 8 – Convert List to Map](https://www.mkyong.com/java8/java-8-convert-list-to-map/) – MadProgrammer Apr 27 '18 at 04:15
  • 2
    Possible duplicate of [Java 8 List into Map](https://stackoverflow.com/questions/20363719/java-8-listv-into-mapk-v) – Jacob G. Apr 27 '18 at 04:16
  • If you're using Guava: `Maps.uniqueIndex(cars, Car::getMake)` – shmosel Apr 27 '18 at 04:23

3 Answers3

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())));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
Shanu Gupta
  • 3,699
  • 2
  • 19
  • 29
  • Slight modification to the question. I actually also want to prepare a Map> makeToCars. How can I achieve this? @Shanu Gupta – sophist_pt Apr 27 '18 at 04:27
1
Map<String, List<Car>> result = 
          myList.stream()
                .collect(Collectors.groupingBy(Car::getMake));
Ousmane D.
  • 54,915
  • 8
  • 91
  • 126
0

You can do it like so

cars.stream()
   .collect(Collectors.toMap(
      car -> car.make,
      Function.identity()
   )
Stefan Zhelyazkov
  • 2,599
  • 4
  • 16
  • 41