Java Collection How to - Replace/Change HashMap items during iteration








Question

We would like to know how to replace/Change HashMap items during iteration.

Answer

import java.util.HashMap;
import java.util.Iterator;
import java.util.Map;
/*w w w  . j av  a 2  s  .  co  m*/
public class Main {

  public static final void main(String[] args) {
    Map<String,String> m = new HashMap<>();
    m.put("a", "alpha");
    m.put("b", "beta");

    Iterator<Map.Entry<String,String>>it = m.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry<String,String> entry = it.next();
      if (entry.getKey() == "b") {
        entry.setValue("new Value");
      }
    }
    it = m.entrySet().iterator();
    while (it.hasNext()) {
      Map.Entry<String,String> entry = it.next();
      System.out.println("key = " + entry.getKey() + ", value = "
          + entry.getValue());
    }
  }
}

The code above generates the following result.