Reverse HashMap keys and values in Java

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

    private  Map invertMap(Map map) {
        Map reverseMap = new HashMap<>();
        for (Map.Entry entry : map.entrySet()) {
            reverseMap.put(entry.getValue(), entry.getKey());
        }
        return reverseMap;
    }
    

    It's important to remember that put replaces the value when called with the same key. So if you map has two keys with the same value only one of them will exist in the inverted map.

提交回复
热议问题