Remove Duplicate keys From Map in Java.

To Remove Duplicate keys From Map in Java we are approaches following scenarios. ConcurrentHashMap is used to store data in key-value pairs.

  • When duplicate keys are used, then previous key will be overwritten from current key.
  • First we create a ConcurrentHashMap object and pass key-value data to them.
  • From keySet() method we find the key and store in Set s.
  • Now we iterate the map and store key and value in one declare parameter.
  • While iterating we get the data object from key.
  • Inside if condition we compare both value and data object.
  • If condition return true then pass key inside remove method to removing duplicate key.
  • Now print the map.
				
					import java.util.Iterator;
import java.util.Set;
import java.util.concurrent.ConcurrentHashMap;

public class RemoveDuplcateMapKey {
	public static void main(String[] args) {
		ConcurrentHashMap<String, Integer> map = new ConcurrentHashMap<String, Integer>();
		map.put("java", 8);
		map.put("Spring", 6);
		map.put("hibernate", 1);
		map.put("java", 9);
		Set s = map.keySet();
		Iterator itr = s.iterator();
		Object key, value;
		System.out.println("After remove duplicate key :-");
		while (itr.hasNext()) {
			key = itr.next();
			value = map.get(key);
			Object data = map.get(key);
			if (value == data) {
				map.remove(key);
			}
			System.out.println(key + " ------- " + data);
		}
	}
}
				
			

Output :-
After remove duplicate key :-
java ——- 9
Spring ——- 6
hibernate ——- 1

Leave a Comment

Your email address will not be published. Required fields are marked *