fork download
  1. import java.util.*;
  2.  
  3. class KeyComparator implements Comparator
  4. {
  5. public int compare(Object a, Object b)
  6. {
  7. if ((char) a > (char) b)
  8. return 1;
  9. else
  10. return -1;
  11. }
  12. }
  13.  
  14. class Tester
  15. {
  16. public static void main(String[] args)
  17. {
  18. //make map.
  19. Map map = new HashMap();
  20. map.put('B', 3);
  21. map.put('A', 1);
  22. map.put('C', 2);
  23.  
  24. //get keylist and sort it.
  25. List keylist = new ArrayList(map.keySet());
  26. Collections.sort(keylist, new KeyComparator());
  27.  
  28. //extract associations and put in a new map.
  29. Map sortedmap = new HashMap();
  30. for (Object key: keylist)
  31. sortedmap.put(key, map.get(key));
  32.  
  33. System.out.print(sortedmap);
  34. }
  35. }
Success #stdin #stdout 0.08s 380160KB
stdin
Standard input is empty
stdout
{A=1, B=3, C=2}