is it possible to change keys of a the same HashMap instance during iteration ? Because map entry set don't have a method entry.setKey(). Now what I can think off is create another HashMap...
MultipartParsingResult parsingResult = parseRequest(request); Map<String, String[]> mpParams = parsingResult.getMultipartParameters(); Map<String, String[]> mpParams2 = new HashMap<String, String[]>(); Iterator<Entry<String,String[]>> it = mpParams.entrySet().iterator(); while (it.hasNext()) { Entry<String,String[]> entry = it.next(); String name = entry.getKey(); if (name.startsWith(portletNamespace)) { mpParams2.put(name.substring(portletNamespace.length(), name.length()), entry.getValue()); } else { mpParams2.put(name, entry.getValue()); } }
It is not allowed to modify a map in Java while iterating over it to avoid non-deterministic behavior at a later stage. For example, the following code example throws a java. util. ConcurrentModificationException since the remove() method of the Map interface is called during iteration.
Well, you can't do it by iterating over the set of values in the Map (as you are doing now), because if you do that then you have no reference to the keys, and if you have no reference to the keys, then you can't update the entries in the map, because you have no way of finding out which key was associated with the ...
How to add new entry while iterating? Create a new Map<String, String> foo instance and set the desired values there. At the end of your process, assign this map to your old map by using map = foo; .
You cannot rename/modify the hashmap key once added. Only way is to delete/remove the key and insert with new key and value pair. Reason : In hashmap internal implementation the Hashmap key modifier marked as final .
Maybe this helps:
map.put(newkey,map.remove(oldkey));
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With