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);
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top