简体   繁体   中英

are the values in a treeMap sorted: java

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.

是的,TreeMap实现了NavigableMap ,它扩展了SortedMap并因此进行了排序(按键)。

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM