0

First of all let me say, please dont answer this by saying "just use a TreeMap" I am aware of TreeMaps but specifically want to learn if the following is possible.

In Java, lets say I have a HashMap of Strings which map to Doubles.

Map<String, Double> map = new HashMap<String, Double>();

And I have inserted some key value pairs into this map. Now let's say I get the keySet:

Collection<String> keys = map.keySet();

My question is, how do I sort the keys collection by the corresponding values in the map? In Perl this would read something like this:

my @keys = sort { $hash{$a} <=> $hash{$b} } keys %hash;

Is there a way to do exactly this in Java using a HashMap?

bfavaretto
  • 71,580
  • 16
  • 111
  • 150
David Williams
  • 8,388
  • 23
  • 83
  • 171
  • Maybe this will help? http://stackoverflow.com/questions/780541/how-to-sort-hash-map – 0x6C38 Apr 01 '13 at 21:13
  • even if you mentioned `treemap`, it won't help you (directly) if you want to sort the map by `value` check the link in my above comment. – Kent Apr 01 '13 at 21:14
  • @bmorris: how is this a duplicate? I want to sort the keys of a map by their corresponding values. That post says to sort a Map. I want to sort a List – David Williams Apr 01 '13 at 21:32

0 Answers0