Java – convert map to map >

I have the map below

Map<String,String> values = new HashMap<String,String>();
values.put("aa","20");
values.put("bb","30");
values.put("cc","20");
values.put("dd","45");
values.put("ee","35");
values.put("ff","35");
values.put("gg","20");

I want to create a new map in the format of map < string, list < string > >, Sample output will be

"20" -> ["aa","cc","gg"]
"30" -> ["bb"]
"35" -> ["ee","ff"]     
"45" -> ["dd"]

I can do this through entity iteration

Map<String,List<String>> output = new HashMap<String,List<String>>();
    for(Map.Entry<String,String> entry : values.entrySet()) {
        if(output.containsKey(entry.getValue())){
            output.get(entry.getValue()).add(entry.getKey());

        }else{
            List<String> list = new ArrayList<String>();
            list.add(entry.getKey());
            output.put(entry.getValue(),list);
          }
    }

Can you do better with streams?

Solution

Groupingby can be used for key grouping If it is used without a mapping collector, the mapping entry stream (stream < map. Entry < string, string >) is converted to map < string, list < map Entry < string, string > > is close to what you want, but not completely

In order to use the value of the output map as a list of original keys, the mapping collector must be linked to the groupingby collector

Map<String,List<String>> output =
    values.entrySet()
          .stream()
          .collect(Collectors.groupingBy(Map.Entry::getValue,Collectors.mapping(Map.Entry::getKey,Collectors.toList())));
System.out.println (output);

Output:

{45=[dd],35=[ee,ff],30=[bb],20=[aa,cc,gg]}
The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>