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));
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…