Win a copy of Learn Spring Security (video course) this week in the Spring forum!
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic

How to remove duplicates values from HashMap

 
abhinas raj
Ranch Hand
Posts: 67
  • Mark post as helpful
  • send pies
  • 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);
}
}

}


}



}
}
 
Henry Wong
author
Marshal
Pie
Posts: 20880
75
C++ Chrome Eclipse IDE Firefox Browser Java jQuery Linux VI Editor Windows
  • Mark post as helpful
  • send pies
  • 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
 
  • Post Reply
  • Bookmark Topic Watch Topic
  • New Topic