Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Remove items from HashMap by key in java

I have one 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 remove the items by their key. I wrote some code that can remove all items with a key equal to some 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 remove all objects with keys equal to my "Another Income", but I want to remove only one object with that key.


2 Answers

You can't put multiple values for a single key in HashMap. You are just overwriting your previous value for this key.

Besides Maps do have a remove methods, which accepts a key and removes the entry for this key.

like image 121
Samuil Yanovski Avatar answered Feb 12 '26 11:02

Samuil Yanovski


A HashMap in Java just holds one value per key.

"Income"           => 4500
"Another Income"   => 6700
"Third Income"     => 2400

So if you ask the HashMap to remove the integer behind the key "Another Incomse", there only is one value which is removed.

The following is not possible with a HashMap!!

"Income"           => 4500
"Another Income"   => 6700
"Another Income"   => 5300
"Third Income"     => 2400

Using this code

HashMap<String, Integer> incomes = new HashMap<String, Integer>();
incomes.put("Income", 4500);
incomes.put("Another Income", 6700);
incomes.put("Another Income", 5300);
incomes.put("Third Income", 2400);

will lead to this:

"Income"           => 4500
"Another Income"   => 5300
"Third Income"     => 2400

since the second time you assign a value to "Another Income", you just overwrite your first entry.

like image 22
Phiwa Avatar answered Feb 12 '26 10:02

Phiwa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!