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:
1 2 3 4 5 6 7 8 9 |
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):
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 |
public class MyComparator implements Comparator<MyClass> { @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; //a<b if(a.charAt(0) < b.charAt(0)) return -1; //a>b 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?