从 Java 中的 HashMap 中删除重复值 [英] Remove duplicate values from HashMap in Java

查看:42
本文介绍了从 Java 中的 HashMap 中删除重复值的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有一个重复值的地图:

I have a map with duplicate values:

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

我想在地图上有

("A", "1");
("B", "2");
("D", "3");

你知道如何去除重复值吗?

Do you know how to get rid of the duplicate values?

目前,我收到java.util.ConcurrentModificationException"错误.

At present, I get 'java.util.ConcurrentModificationException' error.

谢谢.

public static void main(String[] args) {

    HashMap<String, String> map = new HashMap<String, String>();
    map.put("A", "1");
    map.put("B", "2");
    map.put("C", "2");
    map.put("D", "3");
    map.put("E", "3");

    Set<String> keys = map.keySet(); // The set of keys in the map.

    Iterator<String> keyIter = keys.iterator();

    while (keyIter.hasNext()) {
        String key = keyIter.next();
        String value = map.get(key);

        System.out.println(key + "	" + value);

        String nextValue = map.get(key);

        if (value.equals(nextValue)) {
            map.remove(key);
        }
    }
    System.out.println(map);
}

推荐答案

做一个反向HashMap!

make a reverse HashMap!

HashMap<String, String> map = new HashMap<String, String>();
Set<String> keys = map.keySet(); // The set of keys in the map.

Iterator<String> keyIter = keys.iterator();

while (keyIter.hasNext()) {
    String key = keyIter.next();
    String value = map.get(key);
    map.put(value, key);
}

现在您有了 hashMap,您需要将其反转或打印出来.

now that you have the hashMap you need reverse it or print it.

无论如何不要在迭代 hashMap 时删除.将值保存在列表中并在外部循环中删除它们

in anyway do not delete while iterating hashMap. save the values in a list and delete them in an outer loop

这篇关于从 Java 中的 HashMap 中删除重复值的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆