0

I am Using LinkedHashMap for retaining inserted Order of data

My particular function contains This map...

Map retainOrder(){

     Map map= new LinkedHashMap<Long,String>();

     map.put(1L,"A");
     map.put(2L,"B");
     map.put(3L,"C");
     map.put(4L,"D");
     map.put(5L,"E");  
     return map;
}

I am getting output by calling retainOrder() function

1:A
2:B
3:c
4:D
5:E

This is As Expexted

But Sometimes it gives output

    2:B
    3:c
    4:D
    5:E
    1:A

This is Not expected

the problem is that first key becomes last...this is LinkedHashMap doing something wrong. Please give me solution i want to retain order and first value should be first not last.

Nandkumar Tekale
  • 16,024
  • 8
  • 58
  • 85
Oomph Fortuity
  • 5,710
  • 10
  • 44
  • 89

2 Answers2

4

Doc says-

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.

Map<Long, String> map = new LinkedHashMap<Long, String>();

map.put(1L, "A");
map.put(2L, "B");
map.put(3L, "C");
map.put(4L, "D");
map.put(5L, "E");

final Iterator<Long> cursor = map.keySet().iterator();
while (cursor.hasNext()) {
    final Long key = cursor.next();          
    final String value = map.get(key);
    System.out.println(key + "\t" + value);
}

So unless you are changing somewhere in your code the order, it should print as you inserted.

Sajal Dutta
  • 18,272
  • 11
  • 52
  • 74
-1

when number of data is larger than threshold( the capacity * loadFactor), the map will resize and the order will be changed. this is a piece of the sourcecode of HashMap.class:

  void addEntry(int hash, K key, V value, int bucketIndex) {
            Entry<K,V> e = table[bucketIndex];
            table[bucketIndex] = new Entry<>(hash, key, value, e);
            if (size++ >= threshold)
                resize(2 * table.length);
        } 
Daemon
  • 9