-1

Does the LinkedHashMap values collection iterate in insertion order?

Does the LinkedHashMap values collection ( linkedHashMap.values() ) iterate in insertion order?

The documentation states the key set will iterate in insertion order but what about the values collection?

David
  • 15,894
  • 22
  • 55
  • 66
CodingHero
  • 2,865
  • 6
  • 29
  • 42

4 Answers4

2

Yes . It retrieves based on insertion order but it doesnt sort , you can use the TreeMap for that

And the reason for this is because it implements Hashtable and doubly-linked list

Also .values() method returns a collection view of the values contained in this map . it will be in the same order of map implementation

Santhosh
  • 8,181
  • 4
  • 29
  • 56
0

Yes it is also true for values..LinkedHashMap respects insertion order; and the best thing is to make one LinkedHashMap and test it :)

niiraj874u
  • 2,180
  • 1
  • 12
  • 19
0

Yes you can iterate as per insertion order. internally LinkHashMap use 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. (A key k is reinserted into a map m if m.put(k, v) is invoked when m.containsKey(k) would return true immediately prior to the invocation....

Thanks

Kiran Gade
  • 13
  • 1
0

LinkedHashMap has two modes: access-order or insertion-order. This mode is determined during instance instantiation thru one of constructor params. See API for details.

Evgeniy Dorofeev
  • 133,369
  • 30
  • 199
  • 275