Reverse HashMap keys and values in Java

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

    To answer your question on how you can do it, you could get the entrySet from your map and then just put into the new map by using getValue as key and getKey as value.

    But remember that keys in a Map are unique, which means if you have one value with two different key in your original map, only the second key (in iteration order) will be kep as value in the new map.

提交回复
热议问题