Sorting map keys by comparing it's values


/ Published in: Java
Save to your folder(s)

This demonstrate the expressiveness of Groovy vs Java.


Copy this code and paste it in your HTML
  1. import java.util.*;
  2.  
  3. //
  4. // Groovy version of "Sort keys by values" is:
  5. // keys.sort{ lang[it] }
  6. // That's one line replacement!!!
  7. //
  8.  
  9. class MapSort {
  10. public static void main(String[] args){
  11. Map lang = new HashMap();
  12. lang.put(0, "Java");
  13. lang.put(1, "Groovy");
  14. lang.put(2, "Ruby");
  15. lang.put(3, "Python");
  16. lang.put(4, "C#");
  17. lang.put(5, "C++");
  18. lang.put(6, "Perl");
  19.  
  20. List keys = new ArrayList(lang.keySet());
  21.  
  22. //Sort keys by values.
  23. final Map langForComp = lang;
  24. Collections.sort(keys,
  25. new Comparator(){
  26. public int compare(Object left, Object right){
  27. Integer leftKey = (Integer)left;
  28. Integer rightKey = (Integer)right;
  29.  
  30. String leftValue = (String)langForComp.get(leftKey);
  31. String rightValue = (String)langForComp.get(rightKey);
  32. return leftValue.compareTo(rightValue);
  33. }
  34. });
  35.  
  36. //List the key value
  37. for(Iterator i=keys.iterator(); i.hasNext();){
  38. Object k = i.next();
  39. System.out.println(k + " " + lang.get(k));
  40. }
  41. }
  42. }

Report this snippet


Comments

RSS Icon Subscribe to comments

You need to login to post a comment.