Does the LinkedHashMap values collection iterate in insertion order? [duplicate]

StackOverflow https://stackoverflow.com/questions/23389088

  •  12-07-2023
  •  | 
  •  

Domanda

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?

È stato utile?

Soluzione

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

Altri suggerimenti

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

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

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.

Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top