Rather than creating a SortedSet
for just the keys and looking up the value for each key, you can use a SortedMap
and iterate over the map's entries. The map can be sorted in reversed order using the Comparator.reversed()
comparator.
Map<Float, String> mylist = new HashMap<>();
mylist.put(10.5, a);
mylist.put(12.3, b);
mylist.put(5.1, c);
SortedMap<Float, String> orderlist = new TreeMap<Float>(Comparator.reversed());
orderlist.putAll(mylist);
for (Map.Entry<Float, String> e : orderlist.entrySet()) {
System.out.println(e.getKey() + " " + e.getValue());
}
If you aren't using mylist
as a HashMap
separately from this iteration, the SortedMap
can be used directly.
SortedMap<Float, String> mylist = new TreeMap<>(Comparator.reversed());
mylist.put(10.5, a);
mylist.put(12.3, b);
mylist.put(5.1, c);
for (Map.Entry<Float, String> e : mylist.entrySet()) {
System.out.println(e.getKey() + " " + e.getValue());
}