Remove duplicate values from HashMap in Java

前端 未结 10 942
南旧
南旧 2020-12-09 21:02

I have a map with duplicate values:

(\"A\", \"1\");
(\"B\", \"2\");
(\"C\", \"2\");
(\"D\", \"3\");
(\"E\", \"3\");

I would like to the map

10条回答
  •  庸人自扰
    2020-12-09 21:56

    public static void main(String[] args) {
        Map map = new HashMap<>();
        map.put("A", "1");
        map.put("B", "2");
        map.put("C", "2");
        map.put("D", "3");
        map.put("E", "3");
        System.out.println("Initial Map : " + map);
        for (String s : new ConcurrentHashMap<>(map).keySet()) {
            String value = map.get(s);
            for (Map.Entry ss : new ConcurrentHashMap<>(map)
                    .entrySet()) {
                if (s != ss.getKey() && value == ss.getValue()) {
                    map.remove(ss.getKey());
                }
            }
        }
        System.out.println("Final Map : " + map);
    }
    

提交回复
热议问题