How to remove duplicate key-value pairings in a map

Here we are removing duplicate key-value pairings in a map.

  • ConcurrentHashMap class is part of the Collection framework in Java.we are inserting data key with value in ConcurrentHashMap.from keyset.
  • We find the key of that map and remove duplicate key.
  • Now we iterate that set from iterator method and from hasNext method we find next element.
  • After that itr.next method give the key,
  • from key we got the value and data of object type.
  • We comparing both value and data if data and value is equal then we remove key and value.
				
					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("aa", 8);
		map.put("bb", 6);
		map.put("cc", 1);
		map.put("aa", 8);
		Set s = map.keySet();
		Iterator itr = s.iterator();
		Object key, value;
		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:-
aa ——- 8
bb ——- 6
cc ——- 1