Reverse HashMap keys and values in Java

前端 未结 8 1788
梦谈多话
梦谈多话 2020-11-27 17:59

It\'s a simple question, I have a simple HashMap of which i want to reverse the keys and values.

HashMap myHashMap = new HashMap<         


        
8条回答
  •  情深已故
    2020-11-27 18:14

    If the values are not unique, the safe way to inverse the map is by using java 8's groupingBy function

    Map map = new HashMap<>();
    map.put("a",1);
    map.put("b",2);
    
    Map> mapInversed = 
    map.entrySet()
       .stream()
       .collect(Collectors.groupingBy(Map.Entry::getValue, Collectors.mapping(Map.Entry::getKey, Collectors.toList())))
    

提交回复
热议问题