How to traverse and update a Collection like HashMap in java dynamically?

492 Views Asked by At

I need a data structure like HashMap or any other Collection, which will be updated during the traversal. I tried to traverse HashMap, ConcurrentHashMap and LinkedHashMap using Iterator, but I am not able get result. Snippet of the code is:

Map<String, String> linkscoll = new ConcurrentHashMap<String, String>();
linkscoll.put("ABC", "ABC");
for(Iterator it = linkscoll.entrySet().iterator(); it.hasNext(); )
{
   Map.Entry entry = (Map.Entry)it.next();
   String temp = (String) entry.getValue();
   System.out.println(temp);
   linkscoll.put("DEF", "DEF");
}

My output should be:
ABC
DEF

But it is giving output as ABC

I am really need of this. Please help me. Thanks.

3

There are 3 best solutions below

0
On BEST ANSWER

I don't believe you can with a plain HashMap. It is possible to iterate a LinkedHashMap because it preserves insertion order. The linked LinkedHashMap Javadoc says (in part)

The iterators returned by the iterator method of the collections returned by all of this class's collection view methods are fail-fast: if the map is structurally modified at any time after the iterator is created, in any way except through the iterator's own remove method, the iterator will throw a ConcurrentModificationException. Thus, in the face of concurrent modification, the iterator fails quickly and cleanly, rather than risking arbitrary, non-deterministic behavior at an undetermined time in the future.

0
On

You need to use iterator (java.util.Iterator) (See Here) But if you want to modify anything then you have to do it using the iterator only otherwise you will get concurrentModificationException.

0
On

Try this:

for (Map.Entry<KeyObject, ValueObject> entry : yourHashMap.entrySet()){
    ValueObject thisObject = entry.getValue();
    ///Do stuff to thisObject
}