Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Changing HashMap keys during iteration

Tags:

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());     } } 
like image 371
lisak Avatar asked Nov 21 '10 00:11

lisak


People also ask

Can we modify HashMap while iterating?

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.

Can we update map while iterating?

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 ...

Can we add a new entry to HashMap while iterating?

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; .

Can we modify key in HashMap?

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 .


1 Answers

Maybe this helps:

map.put(newkey,map.remove(oldkey)); 
like image 112
Tolga Yılmaz Avatar answered Oct 04 '22 04:10

Tolga Yılmaz