Question

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.

Was it helpful?

Solution

It is sorted: Treemap.values()

The collection's iterator returns the values in ascending order of the corresponding keys.

OTHER TIPS

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);
Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top