Thursday, April 8, 2010

Easiest way to sort a Map in JAVA


Comparator<Integer> comparer = new Comparator<Integer>() {

public int compare(Integer o1, Integer o2) {
return o1.compareTo(o2);
}
};

// hours
Map<Integer, String> hoursUnsorted = new HashMap<Integer, String>();
for (int i = 1; i <= 12; i++) {
if (i <= 9) {
hoursUnsorted.put(i, "0" + i);
} else {
hoursUnsorted.put(i, "" + i);
}
}
Map<Integer, String> hours = new TreeMap<Integer, String>(comparer);
hours.putAll(hoursUnsorted);

No comments:

Post a Comment