Utility method to sort HashMap

A Simple utility method to sort values or keys in a hashMap. Here in the example, I am sorting by values, we can also sort by keys. For that in Compartor, user getkey() instead of getValue() method. Here in the method parameter, boolean value order true means ASC and false means DESC


private static Map sortByComparator(Map unsortMap, final boolean order) {
    List<Map.Entry<String, Integer>> list = new LinkedList<>(unsortMap.entrySet());

    // Sorting the list based on values    
    Collections.sort(list, new Comparator(Map .entry<String, Integer> o1, Map.Entry<String, Integer> o2)
    {
        public int compare(Map.Entry o1, Map.Entry o2)
        {
            if (order)
            {
                return o1.getValue().compareTo(o2.getValue());
            }
            else {
                return o2.getValue().compareTo(o1.getValue());
            }
        }
    });

    // Maintaining insertion order with the help of LinkedList
    Map sortedMap = new LinkedHashMap();
    for (Map.Entry entry : list)
    {
        sortedMap.put(entry.getKey(), entry.getValue());
    }

    return sortedMap;
}

Comments

Popular posts from this blog

AlarmManager and Notification in Android

Open Gallery and get the selected image in appplication

Dismiss or Cancel dialog by swipe gesture