Collectors.groupby for Map<String,List<String>
Currently, you're streaming over the map values (which I assume is a typo), based on your required output you should stream over the map entrySet
and use groupingBy
based on the map value's and mapping
as a downstream collector based on the map key's:
Map<String, List<String>> result = map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey,
Collectors.toList())));
You could also perform this logic without a stream via forEach
+ computeIfAbsent
:
Map<String, List<String>> result = new HashMap<>();
map.forEach((k, v) -> result.computeIfAbsent(v, x -> new ArrayList<>()).add(k));
You can use Collectors.mapping
with Collectors.groupingBy
on the entrySet
of the map as :
Map<String, List<String>> mm = map.entrySet()
.stream()
.collect(Collectors.groupingBy(Map.Entry::getValue,
Collectors.mapping(Map.Entry::getKey, Collectors.toList())));
but it is currently coming as {a1=[a1, a1], a2=[a2]}
That's because you are currently grouping on the values collection which is {a1, a2, a1}
only.