File APIs for Java Developers
Manipulate DOC, XLS, PPT, PDF and many others from your application.
http://aspose.com/file-tools
The moose likes Beginning Java and the fly likes How to remove duplicates values from HashMap Big Moose Saloon
  Search | Java FAQ | Recent Topics | Flagged Topics | Hot Topics | Zero Replies
Register / Login


Win a copy of Spring in Action this week in the Spring forum!
JavaRanch » Java Forums » Java » Beginning Java
Bookmark "How to remove duplicates values from HashMap" Watch "How to remove duplicates values from HashMap" New topic
Author

How to remove duplicates values from HashMap

abhinas raj
Ranch Hand

Joined: Jun 02, 2012
Posts: 47
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
Sheriff

Joined: Sep 28, 2004
Posts: 18896
    
  40

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


Books: Java Threads, 3rd Edition, Jini in a Nutshell, and Java Gems (contributor)
 
I agree. Here's the link: http://aspose.com/file-tools
 
subject: How to remove duplicates values from HashMap