Reverse HashMap keys and values in Java

前端 未结 8 1787
梦谈多话
梦谈多话 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:19

    Apache commons collections library provides a utility method for inversing the map. You can use this if you are sure that the values of myHashMap are unique

    org.apache.commons.collections.MapUtils.invertMap(java.util.Map map)
    

    Sample code

    HashMap reversedHashMap = MapUtils.invertMap(myHashMap) 
    

提交回复
热议问题