/ Published in: Java
This demonstrate the expressiveness of Groovy vs Java.
Expand |
Embed | Plain Text
import java.util.*; // // Groovy version of "Sort keys by values" is: // keys.sort{ lang[it] } // That's one line replacement!!! // class MapSort { lang.put(0, "Java"); lang.put(1, "Groovy"); lang.put(2, "Ruby"); lang.put(3, "Python"); lang.put(4, "C#"); lang.put(5, "C++"); lang.put(6, "Perl"); //Sort keys by values. return leftValue.compareTo(rightValue); } }); //List the key value } } }
Comments
Subscribe to comments
You need to login to post a comment.

The equivalent Groovy code to the Java shown is actually:
// create Map def lang = [0:"Java", 1:"Groovy", 2:"Ruby", 3:"Python", 4:"C#", 5:"C++", 6:"Perl"] // Sort the keys by value def keys = lang.keySet().sort {lang[it]} // List the key value keys.each { println "${it} ${lang[it]}" }
Also, the Java code for Java 5 and 6 could be more like:
final Map lang = new HashMap() {{ put(0, "Java"); put(1, "Groovy"); put(2, "Ruby"); put(3, "Python"); put(4, "C#"); put(5, "C++"); put(6, "Perl"); }}; List keys = new ArrayList(lang.keySet()); Collections.sort(keys, new Comparator() { public int compare(Integer left, Integer right) { return lang.get(left).compareTo(lang.get(right)) } }); for (Integer k : keys) { System.out.println(k + " " lang.get(k); }
Groovy definitly requires WAY less scaffolding than Java. On the other hand Java is WAY WAY faster than groovy. (Nothing in life comes free ;-)
The equivalent Groovy code to the Java shown is actually:
Also, the Java code for Java 5 and 6 could be more like:
Groovy definitly requires WAY less scaffolding than Java. On the other hand Java is WAY WAY faster than groovy. (Nothing in life comes free ;-)