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):…
Leggi tutto