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.