fork download
  1. import java.util.*;
  2.  
  3. class ValueComparator implements Comparator
  4. {
  5. Map map;
  6. ValueComparator(Map map)
  7. {
  8. this.map = map;
  9. }
  10.  
  11. public int compare(Object a, Object b)
  12. {
  13. if ((double) map.get(a) > (double) map.get(b))
  14. return 1;
  15. else
  16. return -1;
  17. }
  18. }
  19.  
  20. class Tester
  21. {
  22. public static void main(String[] args)
  23. {
  24. //make map.
  25. Map map = new HashMap();
  26. map.put("Beltre", .324);
  27. map.put("Martinez", .335);
  28. map.put("Alluve", .341);
  29. map.put("Brantley", .327);
  30. System.out.println("Unsorted: " + map);
  31.  
  32. //put in a TreeMap.
  33. Comparator comparator = new ValueComparator(map);
  34. Map sortedmap = new TreeMap(comparator);
  35. sortedmap.putAll(map);
  36. System.out.println("Sorted: " + sortedmap);
  37. }
  38. }
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
Unsorted: {Brantley=0.327, Martinez=0.335, Alluve=0.341, Beltre=0.324}
Sorted: {Beltre=0.324, Brantley=0.327, Martinez=0.335, Alluve=0.341}