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?
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>
.
Collected from the Internet
Please contact [email protected] to delete if infringement.
Comments