Return to Snippet

Revision: 3095
at June 3, 2007 12:33 by thebugslayer


Initial Code
import java.util.*;

//
// Groovy version of "Sort keys by values" is:
//    keys.sort{ lang[it] }
// That's one line replacement!!!
//

class MapSort {
	public static void main(String[] args){
		Map lang = new HashMap();
		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");
		
		List keys = new ArrayList(lang.keySet());
		
		//Sort keys by values.
		final Map langForComp = lang;
		Collections.sort(keys, 
			new Comparator(){
				public int compare(Object left, Object right){
					Integer leftKey = (Integer)left;
					Integer rightKey = (Integer)right;
					
					String leftValue = (String)langForComp.get(leftKey);
					String rightValue = (String)langForComp.get(rightKey);
					return leftValue.compareTo(rightValue);
				}
			});
		
		//List the key value
		for(Iterator i=keys.iterator(); i.hasNext();){
			Object k = i.next();
			System.out.println(k + " " + lang.get(k));
		}
	}
}

Initial URL

                                

Initial Description
This demonstrate the expressiveness of Groovy vs Java.

Initial Title
Sorting map keys by comparing it's values

Initial Tags
groovy

Initial Language
Java