user592704
user592704

Reputation: 3704

ConcurrentHashMap with add effect

I just tried to get add effect with ConcurrentHashMap<String,String> but the elements order is mixed. Code like a...

ConcurrentHashMap<String,String>h=new ConcurrentHashMap<String,String>();

        for(int i=0; i<10; i++)
        {           
            h.put(""+Math.random(), ""+i);

        }

        Iterator<String> iterator=h.values().iterator();
        while(iterator.hasNext())
        {
            System.out.println(iterator.next());
        }

... gives in console next values:

9
4
6
2
0
5
1
7
3
8

... so my question is...

is there a way for ConcurrentHashMap to get original elements order if key is some random string?

Thanks

Upvotes: 0

Views: 287

Answers (2)

Jigar Joshi
Jigar Joshi

Reputation: 240928

Use LinkedHashMap instead it will preserve the order of insertion

Hash table and linked list implementation of the Map interface, with predictable iteration order.

And use

Collections.synchronizedMap(mapInstance)

See Collections.synchronizedMap(mapINstance);

 Map<K,V> map = Collections.synchronizedMap(new LinkedHashMap());

Upvotes: 11

kosa
kosa

Reputation: 66657

LinkedHashMap maintains the order of insertion.

Hash table and linked list implementation of the Map interface, with predictable iteration order. This implementation differs from HashMap in that it maintains a doubly-linked list running through all of its entries. This linked list defines the iteration ordering, which is normally the order in which keys were inserted into the map (insertion-order). Note that insertion order is not affected if a key is re-inserted into the map.

Upvotes: 1

Related Questions