Domanda

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.

È stato utile?

Soluzione

It is sorted: Treemap.values()

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

Altri suggerimenti

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);
Autorizzato sotto: CC-BY-SA insieme a attribuzione
Non affiliato a StackOverflow
scroll top