Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Behaviour of LinkedHashMap's keySet() and values() methods [duplicate]

Possible Duplicate:
Is the order guaranteed for the return of keySet() of a LinkedHashMap object?

Consider I create a LinkedHashMap, like the following:

Map<String, String> map = new LinkedHashMap<String, String>();
map.put("a", "aa");
map.put("b", "bb");
map.put("c", "cc");

When I call keySet(), does that give me an ordered set? And if I call values(), are these ordered too?

EDIT

Sry, meant ordered, not sorted.

like image 486
helpermethod Avatar asked Mar 06 '12 12:03

helpermethod


2 Answers

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.

like image 65
Tomasz Nurkiewicz Avatar answered Oct 19 '22 13:10

Tomasz Nurkiewicz


You don't get a SortedSet or a sorted collection when retrieving the key set or the values. However, the returned implementations use the map's key/value iterators and thus would return the values in the order of insertion, e.g. when being used in a foreach loop.

Thus you get the order as defined by the LinkedHashMap but you can not necessarily consider that to be sorted (and you can't resort those collections either).

like image 29
Thomas Avatar answered Oct 19 '22 15:10

Thomas