Java – Removes items from HashMap by key in Java

Removes items from HashMap by key in Java… here is a solution to the problem.

Removes items from HashMap by key in Java

I have a HashMap like this

public static HashMap<String, Integer> jsonPosition = new HashMap<String, Integer>();

I put some values like this in my hashmap

GlobalClassParameters.jsonPosition.put("another income",
                        GlobalClassParameters.jsonPosition.size());

Now I want to delete the item by key. I wrote some code that can remove all items with a key equal to a certain value.

Object objectToRemove = null;
Iterator<Map.Entry<String, Integer>> iter = GlobalClassParameters.jsonPosition.entrySet().iterator();

while (iter.hasNext()) {
   Map.Entry<String, Integer> entry = iter.next();

if(entry.getKey().equalsIgnoreCase("another income"))
   {
      objectToRemove = entry;
      break;
   }  
}                               

if(objectToRemove != null)
{
   GlobalClassParameters.jsonPosition.entrySet().remove(objectToRemove);
}

My problem is that I don’t need to delete all objects whose key equals my “another income”, but I only want to delete one object with that key.

Solution

You cannot put multiple values for a single key in a HashMap. You just overwrote the value before that key.

In addition to map, there is a remove method, which accepts a key and delete the entry for that key.

Related Problems and Solutions