0

I have a loop to iterate a hashmap. If the condition is satisfied I need to remove the key, value pair from the hashmap. I am unable to do it using the below code. How can I achieve this?

for(HashMap.Entry<Integer,Character> m:commons.entrySet()){
    while(i!=(int)m.getKey()){
        i++;
    }
    if(s2.charAt(i)!=(int)m.getKey()){
      commons.remove((int)m.getKey());
    }
}
halfer
  • 19,824
  • 17
  • 99
  • 186

2 Answers2

1
for (Iterator<Map.Entry<Integer, Character>> it = map.entrySet().iterator(); it.hasNext(); ) {
    Map.Entry<Integer, Character> entry = it.next();

    // casting to int is redundant in your code. I removed it.
    while (i != entry.getKey()) i++;

    if (s2.charAt(i) != entry.getKey()) {
        it.remove();
    }
}

You can use an Iterator to safely remove while iterating over a Map.

You can also look at .removeIf() (Java 8+), but with a loop inside your iteration, this is more readable, imo.

Harshal Parekh
  • 5,918
  • 4
  • 21
  • 43
1
  1. The way you are trying to do it may cause ConcurrentModificationException. You should use an Iterator or Collection::removeIf which internally uses an Iterator.
  2. Though you can compare a char with an int, probably you have mixed up key and value in the comparison. You have written

    if(s2.charAt(i)!=(int)m.getKey())
    

    in which you are comparing the s2.charAt(i) with the key which is an Integer. Syntactically, it is correct but probably you wanted to compare the value (which is a Characater) i.e. most likely you want to do

    if(s2.charAt(i)!=(int)m.getValue())
    

Do it as follows:

for (Iterator<Entry<Integer, Character>> itr = commons.entrySet().iterator(); itr.hasNext();) {
    Entry<Integer, Character> entry = itr.next();

    while (i != entry.getKey()) {
        i++;
    }

    if (s2.charAt(i) != entry.getValue()) {
        itr.remove();
    }
}
Arvind Kumar Avinash
  • 71,965
  • 6
  • 74
  • 110
  • Thank you Arvind. The concept is clearer for me now – Nikitha Rao May 18 '20 at 21:06
  • I hope the solution worked for you. Do not forget to accept the answer so that future visitors can also use the solution confidently. Check https://meta.stackexchange.com/questions/5234/how-does-accepting-an-answer-work to learn how to do it. Feel free to comment in case of any doubt/issue. – Arvind Kumar Avinash May 18 '20 at 21:07