Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
311 views
in Technique[技术] by (71.8m points)

java - Collectors.groupby for Map<String,List<String>

Forgive me if the solution is very obvious but I can't seem to figure out how to do this

public static void main(String[] args) {
    Map<String, String> map = new HashMap<>();
    map.put("b1", "a1");
    map.put("b2", "a2");
    map.put("b3", "a1");
    Map<String, List<String>> mm = map.values().stream().collect(Collectors.groupingBy(m -> m));
    System.out.println(mm);
}

I want to group by based on values in hashmap. I want the output to be {a1=[b1, b3], a2=[b2]} but it is currently coming as {a1=[a1, a1], a2=[a2]}

See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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));

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...