7

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.

Community
  • 1
  • 1
helpermethod
  • 59,493
  • 71
  • 188
  • 276
  • 1
    It's not a contract written in [Java Doc](http://docs.oracle.com/javase/6/docs/api/java/util/HashMap.html#keySet%28%29). All it guarantees is a Set interface. – Nishant Mar 06 '12 at 12:29
  • 3
    Why not [Use The Source, Luke](http://javasourcecode.org/html/open-source/jdk/jdk-6u23/java.util/LinkedHashMap.java.html)? – DNA Mar 06 '12 at 12:50
  • @DNA the link you gave is now broken :( – GreenGiant Feb 06 '14 at 01:42
  • @GreenGiant Google is your friend ;-) try [this one](http://www.docjar.com/html/api/java/util/LinkedHashMap.java.html) instead. – DNA Feb 06 '14 at 13:41

2 Answers2

8

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.

Community
  • 1
  • 1
Tomasz Nurkiewicz
  • 334,321
  • 69
  • 703
  • 674
  • 1
    Please look at the accepted answer of this question: http://stackoverflow.com/questions/2923856/is-the-order-guaranteed-for-the-return-of-keyset-of-a-linkedhashmap-object – Arne Evertsson Oct 03 '12 at 10:08
  • @ArneEvertsson: +1, thanks, corrected my answer. In fact I marked this question as duplicate. – Tomasz Nurkiewicz Oct 03 '12 at 19:51
2

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

Thomas
  • 87,414
  • 12
  • 119
  • 157