1

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.

Sunny
  • 7,444
  • 22
  • 63
  • 104
  • 1
    TreeMap is sorted by keys, not by values. See these question if you want to sort your Map by values: http://stackoverflow.com/questions/1448369/how-to-sort-a-treemap-based-on-its-values – fluminis Jan 03 '14 at 13:23

3 Answers3

5

It is sorted: Treemap.values()

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

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118
  • ok, so can i do collection.getindex(5)? will it give me the value at the 5th index of this collection – Sunny Jan 03 '14 at 13:23
  • 1
    You could try Collection method `.toArray()`, which returns an array in the same sequence as the iterator. Otherwise, just use the iterator... – vikingsteve Jan 03 '14 at 13:28
  • one more thing. how do i make this array into an array list? – Sunny Jan 03 '14 at 13:31
  • There is no method `collection.getIndex`, so no, you can't call that method. If you want the 5th item in the collection, you'll have to get an `Iterator` for it and call `next()` five times (four to "fast forward" through the first four, and then the fifth one to get at your value). Of course, you should be sure there are at least five values, or else you'll get a `NoSuchElementException`. – yshavit Jan 03 '14 at 13:31
2

Yes, TreeMap implements NavigableMap, which extends SortedMap and is thus sorted (by key).

vikingsteve
  • 38,481
  • 23
  • 112
  • 156
0

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);
Aris2World
  • 1,214
  • 12
  • 22