It is sorted: Treemap.values()
The collection's iterator returns the values in ascending order of the corresponding keys.
سؤال
I am using a treeMap in java. I want to get a sorted list/collection of all the values. Would TreeMap.values() do the trick?
The collection that i get, would it be sorted based on the keySet, or would this collection be random.
Thanks.
المحلول
It is sorted: Treemap.values()
The collection's iterator returns the values in ascending order of the corresponding keys.
نصائح أخرى
Yes, TreeMap implements NavigableMap
, which extends SortedMap
and is thus sorted (by key).
As stated in javadoc of TreeMap.values():
The collection's iterator returns the values in ascending order of the corresponding keys
So the collection returned can be iterated in ascending order of the keys.
To achieve more flexible way to sort the values of a map I usually use the following pattern:
List listOfValues = new ArrayList();
Comparator valuesComparator = ...;
listOfValues.addAll(myTreeMap.values());
Collections.sort(listOfValues, valuesComparator);