Sorter :
I have a map Map<String, Set<String>>
Map<String, Set<String> result = map.entrySet().parallelStream().collect(
Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toSet())));
I want to convert it to Map<String, Set<String>>
. by grouping the values and swapping the places of key and value.
But this line gives me
Type mismatch: cannot convert from Map<Object,Set<Object>> to Map<String,Set<String>>
Andy Turner :
The problem that you've got here is the type of the map you are creating is:
Map<Set<String>, Set<String>>
not Map<String, Set<String>>
.
As such, you need to expand the map's values first, for example:
Map<String, Set<String>> collect = map.entrySet()
.parallelStream()
// Expand (k, {v1, v2, v3}) to [(v1, k), (v2, k), (v3, k)]
.flatMap(e -> e.getValue().stream().map(ee -> new SimpleEntry<>(ee, e.getKey())))
.collect(
Collectors.groupingBy(
Map.Entry::getKey,
Collectors.mapping(Map.Entry::getValue, Collectors.toSet())));
Unless you really need the parallel processing, I think it would be much easier to use loops:
Map<String, Set<String>> collect = new HashSet<>();
for (Map.Entry<String, Set<String>> entry : map.entrySet()) {
for (String v : entry.values()) {
collect.computeIfAbsent(v -> new HashSet<>())
.add(entry.getKey()));
}
}