从Java中的HashMap中删除重复的值

从Java中的HashMap中删除重复的值

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

问题描述

我有一个重复值的地图:

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

我想要的地图有

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

你知道如何摆脱重复的值?



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



谢谢。

  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);

设置< String> keys = map.keySet(); //地图中的一组键。

迭代器< String> keyIter = keys.iterator();

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

System.out.println(key +\t+ value);

String nextValue = map.get(key);

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


解决方案

使反向HashMap! / p>

  HashMap< String,String> map = new HashMap< String,String>(); 
设置< String> keys = map.keySet(); //地图中的一组键。

迭代器< String> keyIter = keys.iterator();

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

现在你有你需要的hashMap或者打印它。无论如何

在迭代hashMap时不要删除。将值保存在列表中,并在外部循环中删除它们


I have a map with duplicate values:

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

I would like to the map to have

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

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

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

Thank you.

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 + "\t" + value);

        String nextValue = map.get(key);

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

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.add(value, key);
}

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

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

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

08-18 15:49