Sorting a Java Map
Hi,
a short post to show a simple tip useful when dealing with Java Maps.
The following Function sorts a Map through a custom Comparator and returns a new ordered LinkedHashMap:
public static Map sortMapByKey(Map map, Comparator comparator) {
List list = new LinkedList(map.keySet());
Collections.sort(list, comparator);
Map result = new LinkedHashMap();
for (Object o : list) {
result.put(o, map.get(o));
}
return result;
}
And this is an example of Comparator for MyClass objects sorted on the base of a String property “sortField” (note the toLowerCase method):
public class MyComparator implements Comparator {
@Override
public int compare(MyClass arg0, MyClass arg1) {
if (arg0.getSortField() == null || arg1.getSortField() == null)
return 0;
String a = (arg0.getSortField()).toLowerCase();
String b = (arg1.getSortField()).toLowerCase();
return compareStringFirstChar(a, b);
}
private int compareStringFirstChar(String a, String b) {
//a=b
if(a == null || b == null || a.isEmpty() || b.isEmpty())
return 0;
//ab
else if (a.charAt(0) > b.charAt(0))
return 1;
//zero a=b
else
return compareStringFirstChar(a.substring(1), b.substring(1));
}
}
The sorting Function is general and is possible to implement a custom Comparator depending on the specific needs.
Ciao
Fede
Una risposta.
hi,
why don’t you use the String.compareTo(String) method?
Has “compareStringFirstChar” better performance?