Thursday, February 2, 2012

How to Sort HashMap by Values in Java

Recently I had a task that requires me to work with HashMap. One of the task is to sort the content of a HashMap by its values. I use a HashMap to store a user-defined Object. Therefore, I need to make the user-defined Object "sortable" by implementing Comparable interface first. In this example, the user-defined object is Summary.

This is how I sort a HashMap:


    public HashMap sortSummary(HashMap listOfSummary) {
        HashMap sortedListOfSummary = new LinkedHashMap();

        ArrayList keys = new ArrayList();
        keys.addAll(listOfSummary.values());
        Collections.sort(keys, Collections.reverseOrder());
        int size = keys.size();
        for (int i = 0; i < size; i++) {
            Summary summary = (Summary) keys.get(i);
            sortedListOfSummary.put(summary.getUrl(), summary);
        }

        return sortedListOfSummary;
    }

I've seen several codes in the Internet that use TreeMap to sort a HashMap, so this code could be another alternative in dealing with such kind of task.

PS: I don't know how to format my code in Blogger. If anyone now how to do it, please let me know.

No comments:

Post a Comment