I am trying to replace whole key/value pair from my LinkedHashMap but seems it is not working. I am getting concurrentmodificationexception. Is there a way to replace whole key/value pair for a key at the same position without any major changes.
I tried to do the following:
Map<String, String> testMap = new LinkedHashMap<String, String>();
testMap.put("1", "One");
testMap.put("2", "Two");
testMap.put("3", "Three");
testMap.put("4", "Four");
testMap.put("5", "Five");
testMap.put("6", "Six");
/*
* Removing an element from the Map.
*/
Iterator<Entry<String, String>> iter = testMap.entrySet().iterator();
while (iter.hasNext()) {
Map.Entry<String, String> entry = (Map.Entry<String, String>) iter.next();
System.out.print(entry.getKey() + "->" + entry.getValue() + "; ");
if (entry.getKey().equals("1"))
iter.remove(); // remove one entry (key/value) with key "1". Ok
if (entry.getValue().equalsIgnoreCase("Two"))
iter.remove(); // removing all entries (key/value) for value "Two". Ok
if (entry.getKey().equals("3"))
entry.setValue("Updated_Three"); // Updating value for key 3. Ok
// Below how to now add a new key/value pair in my testMap at this position
// without affecting any other order?
if (entry.getKey().equals("4")) {
iter.remove();
// How to now add a new key/value pair at this position without affecting any
// other order.
// testMap.put("44", "FourFour"); // Removing entry with key 4 and adding a new
// key/valuepair to hashmap. It throws ConcurrentModificationException. Any
// other way to perform this?
}
}