Reputation: 4740
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?
Upvotes: 1
Views: 108
Reputation: 15423
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())));
Upvotes: 2
Reputation: 45309
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()])));
Upvotes: 1
Reputation: 27971
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>
.
Upvotes: 3