Is the Order Guaranteed for the Return of Keys and Values from a Linkedhashmap Object

Is the order guaranteed for the return of keys and values from a LinkedHashMap object?

The Map interface provides three
collection views, which allow a map's contents to be viewed as a set
of keys, collection of values, or set
of key-value mappings. The order of
a map is defined as the order in which
the iterators on the map's collection
views return their elements. Some map
implementations, like the TreeMap
class, make specific guarantees as to
their order; others, like the
HashMap class, do not.

-- Map

This linked list defines the iteration
ordering, which is normally the order
in which keys were inserted into the
map (insertion-order).

-- LinkedHashMap

So, yes, keySet(), values(), and entrySet() (the three collection views mentioned) return values in the order the internal linked list uses. And yes, the JavaDoc for Map and LinkedHashMap guarantee it.

That is the point of this class, after all.

Retrieving KeySet from LinkedHashMap in specified order

A TreeSet is not about preserving insertion order. It is about sorting its elements.

In other words: if you add String objects to a TreeSet, they get ordered as if you would be sorting that list!

So, if order is your primary concern, you should use the LinkedHashSet instead of TreeSet! Alternatively, you could provide a custom Comparator upon creating your TreeSet ... that somehow gives you that order you are looking for - that might work, but smells like hackish workaround to me.

Does entrySet() in a LinkedHashMap also guarantee order?

According to the Javadocs, yes.

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).

As for the edit, no, it should work just fine. But the entry set is somewhat faster since it avoids the overhead of looking up every key in the map during iteration.

Is the order of values retrieved from a HashMap the insertion order

The values are printed in the order in which they have been inserted. Is this true in general? I was expecting the values to be printed in random order.

The HashMap API does not define the order of iteration.

However, if you look at the implementation of HashMap, you can deduce that there is a complex transient relationship between the iteration order, the keys' hash values, the order in which the keys were inserted and the size of the hashtable. This relationship gets scrambled if the hashtable resizes itself.

In your case, you are using Integer keys which means that the hash values of the keys are the key values themselves. Also, you inserted the entries in key order. This leads (fortuitously!) to the iteration order matching the insertion order. But if you kept inserting more keys, you would find that the iteration order "wraps around". Then as the table goes through a series of resizes, the order will get progressively more and more scrambled.

In short, what you are seeing is an artefact of the hashtable implementation, and not something that you can (or should) sensibly make use of. Not least because it could change from one Java release to the next.

Does the LinkedHashMap values collection iterate in insertion order?

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

Method to extract all keys from LinkedHashMap into a List

The ordering is important which is why I don't think I can use myMap.keySet() which is a Set

The Map#keySet() method for LinkedHashMap will return the set in insertion order. Here's a quote from Map documentation:

The order of a map is defined as the order in which the iterators on the map's collection views return their elements. Some map implementations, like the TreeMap class, make specific guarantees as to their order; others, like the HashMap class, do not.

So, you don't need to write a separate method for that. Methods like keySet() and entrySet() will return the entries in the insertion order only.


Well, if you really want a List<Keys>, then you can directly do:

List<Long> keys = new ArrayList<>(target.keySet());

.. wherever you want a List. You don't need the method at all.

Does java manipulate the order of keys in map before sending via REST Api?

Documentation of LinkedHashMap

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. (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.)

The LinkedHashMap in Java will maintain the ordering for insertion. If you read the key-value pairs from an ordered list and insert this into a LinkedHashMap in the same order, then the arrangement will be preserved.

That said, if you're reading this in from a JSON, then the ordering of pairs should be considered un-ordered

From the JSON specification RFC 8259:

An object is an unordered collection of zero or more name/value
pairs, where a name is a string and a value is a string, number,
boolean, null, object, or array.

Further:

JSON parsing libraries have been observed to differ as to whether or
not they make the ordering of object members visible to calling
software. Implementations whose behavior does not depend on member
ordering will be interoperable in the sense that they will not be
affected by these differences.

If you need a workaround then you can follow the answer provided by clayton.carmo. This workaround works by converting the JSON object form into a JSON array of key-value objects. This is guaranteed to maintain ordering. From the RFC documentation:

An array is an ordered sequence of zero or more values.

Behaviour of LinkedHashMap's keySet() and values() methods

First of all LinkedHashMap is ordered but not sorted. TreeMap is sorted (and hence ordered as well).

That being said you can not expect the output of keySet() and values() to be sorted. Actually the JavaDoc says nothing about the order (as it turns out, the order is guaranteed by JavaDoc: Is the order guaranteed for the return of keys and values from a LinkedHashMap object?) of these collections, however looking at the implementation they should follow the order of underlying Map.

To address recent edit to your question: it is not part of the contract, in fact LinkedHashMap does not even implement keySet() and values() but uses base classes's (HashMap) version. Even though based on the implementation you can see the order is preserved, you should not depend on it if you want your application to be portable.



Related Topics



Leave a reply



Submit