.:: CODE SNIPPET ::.

"Your time is limited, so don't waste it living someone else's life"

How to sort a Map in java


In this post, I have an Map need to be sorted named map declared as below:

Map<String, String> map = new HashMap<String, String>();
map.put("Monday", "Go to school");
map.put("Tuesday", "Have picnic with friends");
map.put("Wednesday", "work with my parent");
map.put("Thursday", "come to visit my grandfather");
map.put("Friday", "Join guitar club");

As you know, we have a couple of (key,value) in an entry of map, so we now sort them in turn.
Sort by the key
It’s simply you use class Collections as below:

private Map<String, String> sort(Map<String, String> inputMap)
    {
        List<String> messages = new ArrayList<String>(map.keySet());
        Collections.sort(messages);
        Map<String, String> sortedMap = new TreeMap<String, String>();
        for (String str : messages)
        {
            sortedMap.put(str, map.get(str));
        }
        return sortedMap;
    }

Sort by the value
In case of value, you should use a comparator class.

class StringComparator implements Comparator<String>
    {

        /** The map. */
        private final Map<String, String> map;

        /**
         * Instantiates a new string comparator.
         *
         * @param map the map
         */
        public StringComparator(final Map<String, String> map)
        {
            this.map = map;
        }

        @Override
        public int compare(String arg0, String arg1)
        {
            int temp = this.map.get(arg0).compareTo(this.map.get(arg1));
            return temp == 0 ? 1 : temp;
        }
    }

Next, in your own sort function you use that class as an comparator for the map:

private Map<String, String> sortLstMessageBySF(Map<String, String> map)
    {
        if (map == null)
        {
            return null;
        }
        StringComparator comparator = new StringComparator(map);
        Map<String, String> sortedMap = new TreeMap<String, String>(comparator);
        sortedMap.putAll(map);
        return sortedMap;
    }

So, now we have the ways to sort a map with by either key and value.
But, it is for the simple data type, String for detailed, how about more complex data type such an simple object names Job

public class Job
{
    private final String name;

    public Job(final String name)
    {
        this.name = name;
    }
    
    public synchronized String getName()
    {
        return name;
    }
}

In this case, we can recognize the ability of the comparator class. With this, we just do a few things. First, we have also a Map like:

Map<String, Job> map = new HashMap<String, Job>();
map.put("Monday", new Job("Go to school"));
map.put("Tuesday", new Job("Have picnic with friends"));
map.put("Wednesday", new Job("work with my parent"));
map.put("Thursday", new Job("come to visit my grandfather"));
map.put("Friday", new Job("Join guitar club"));

Now if you want to sort by the key, it is similar the above ( the data type is String).
Continue with the value, we get some small change with the comparator class:

class StringComparator implements Comparator<String>
    {

        /** The map. */
        private final Map<String, Job> map;

        /**
         * Instantiates a new string comparator.
         *
         * @param map the map
         */
        public StringComparator(final Map<String, Job> map)
        {
            this.map = map;
        }

        @Override
        public int compare(String arg0, String arg1)
        {
            int temp = this.map.get(arg0).getName().compareTo(this.map.get(arg1).getName());
            return temp == 0 ? 1 : temp;
        }
    }

So, the rest work we have to do is:

private Map<String, Job> sortLstMessageBySF(Map<String, Job> map)
    {
        if (map == null)
        {
            return null;
        }
        StringComparator comparator = new StringComparator(map);
        Map<String, Job> sortedMap = new TreeMap<String, Job>(comparator);
        sortedMap.putAll(map);
        return sortedMap;
    }
Advertisements

Leave a Reply

Fill in your details below or click an icon to log in:

WordPress.com Logo

You are commenting using your WordPress.com account. Log Out / Change )

Twitter picture

You are commenting using your Twitter account. Log Out / Change )

Facebook photo

You are commenting using your Facebook account. Log Out / Change )

Google+ photo

You are commenting using your Google+ account. Log Out / Change )

Connecting to %s

%d bloggers like this: