Friday, February 20, 2009

Tip: Sort a map by values

A handy tip to sort map by values.

//:~
package samples.core.java;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class SortMapByValueExample {
public static void main(String[] args) {
Map map = new TreeMap();
map.put("1", "100");
map.put("10", "50");
map.put("100", "40");
map.put("1000", "10000");

List keys = new ArrayList(map.keySet());
ByValueComparator bvc = new SortMapByValueExample().new ByValueComparator(
map);
Collections.sort(keys, bvc);
Iterator iterator = keys.iterator();
while (iterator.hasNext()) {
String key = (String) iterator.next();
System.out.println(key + "-" + map.get(key));
}
}

private class ByValueComparator implements Comparator {
private Map map;

public ByValueComparator(Map map) {
this.map = map;
}

public int compare(Object o1, Object o2) {
int integer = Integer.parseInt((String) this.map.get((String) o1));
int otherInteger = Integer.parseInt((String) this.map
.get((String) o2));
return -1
* (new Integer(integer)
.compareTo(new Integer(otherInteger)));
}
}
}


No comments: