• Post Reply Bookmark Topic Watch Topic
  • New Topic
programming forums Java Mobile Certification Databases Caching Books Engineering Micro Controllers OS Languages Paradigms IDEs Build Tools Frameworks Application Servers Open Source This Site Careers Other Pie Elite all forums
this forum made possible by our volunteer staff, including ...
Marshals:
  • Campbell Ritchie
  • Jeanne Boyarsky
  • Ron McLeod
  • Paul Clapham
  • Liutauras Vilda
Sheriffs:
  • paul wheaton
  • Rob Spoor
  • Devaka Cooray
Saloon Keepers:
  • Stephan van Hulst
  • Tim Holloway
  • Carey Brown
  • Frits Walraven
  • Tim Moores
Bartenders:
  • Mikalai Zaikin

How to remove duplicates values from HashMap

 
Ranch Hand
Posts: 74
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator
i am trying to remove the duplicate values from HashMap by the following code but it is thwoing following exception

java.util.ConcurrentModificationException how to remove duplicate values ?




import java.util.Enumeration;
import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

public class Map_iterator {

public static void main(String[] args){

HashMap<String,Integer> hm=new HashMap<String,Integer>();
hm.put("AK",1);
hm.put("BK",2);
hm.put("CK",3);
hm.put("DK",4);
hm.put("EK",5);
hm.put("FK",6);
hm.put("GK",7);
hm.put("HK",6);
hm.put("IK",7);


System.out.println("values are "+hm.values());

// Removing the duplicate VALUES from Map
System.out.println("\n After removing duplicate values ");

for(Object key1:hm.keySet()){

for(Object key2:hm.keySet()){
if(!key1.toString().equals(key2.toString())){
int x=hm.get(key1);
int y=hm.get(key2);
if(x==y){
hm.remove(key2);
}
}

}


}



}
}
 
author
Posts: 23951
142
jQuery Eclipse IDE Firefox Browser VI Editor C++ Chrome Java Linux Windows
  • Mark post as helpful
  • send pies
    Number of slices to send:
    Optional 'thank-you' note:
  • Quote
  • Report post to moderator

abhinas raj wrote:i am trying to remove the duplicate values from HashMap by the following code but it is thwoing following exception

java.util.ConcurrentModificationException how to remove duplicate values ?






Basically, you are not allowed to directly modify the collection while you are iterating through the collection.

You can only modify the collection via the iterator, while iterating through the collection. And of course, you don't have access to the iterator because you are using the for-each loop. You need to switch it to the regular for loop, and modify the collection via the iterator only.

Henry
reply
    Bookmark Topic Watch Topic
  • New Topic