1

I am trying to learn to do this in Java 8 using streams.

Given the follow:

List<PartModel> models = new ArrayList<>();
models.add(new PartModel("Part1", "AModel"));
models.add(new PartModel("Part1", "BModel"));
models.add(new PartModel("Part2", "AModel"));

I would like to convert this list into a map: Map<String, Set<String> where the values would be:

"Part1" -> ["AModel", "BModel"]
"Part2" -> ["AModel"]

How can I achieve this with using a Java 8 stream?

Stefan Zobel
  • 3,182
  • 7
  • 28
  • 38
crmepham
  • 4,676
  • 19
  • 80
  • 155
  • 1
    Possible duplicate of [Java: How to convert List to Map](https://stackoverflow.com/questions/4138364/java-how-to-convert-list-to-map) – fantaghirocco Oct 19 '18 at 10:14

3 Answers3

3

You can use the groupingBy collector like this:

Map<String, Set<String>> partModelMap = models.stream()
      .collect(Collectors.groupingBy(Partmodel::getPart,
               Collectors.mapping(Partmodel::getModel, Collectors.toSet())));

The Collectors.mapping part will map the values of the map from List<PartModel> to a Set<String>.

marstran
  • 26,413
  • 5
  • 61
  • 67
2

We can group by getPart() and then return a Map<Integer, Set<String>>

Map<Integer, Set<String>> collect = models.stream()
                .collect(Collectors.groupingBy(PartModel::getPart, 
                Collectors.mapping(PartModel::getModel), Collectors.toSet())));
Nicholas K
  • 15,148
  • 7
  • 31
  • 57
1

A simple stream grouping by the first field and transforming the groups can look like this:

    Map<String, String[]> map = models.stream()
        .collect(Collectors.groupingBy(PartModel::getPartName,
                Collectors.mapping(PartModel::getModelName, Collectors.toList())))
        .entrySet().stream()
        .collect(Collectors.toMap(Entry::getKey, 
        entry -> entry.getValue().toArray(new String[entry.getValue().size()])));
ernest_k
  • 44,416
  • 5
  • 53
  • 99