Sorting a HashMap in Java: SortedMap to the rescue!

java-sorting

I recently had to populate a list and make sure there were no duplicates so I immediately thought of a hash map. While this worked great, I also needed the output to be sorted alphabetically. This is where SortedMap comes into play.

While I could have done this a few ways, I found this method very simple and straightforward. The hash map provides the unique values while the SortedMap provides the auto sorting I needed. I only had about 1000 records to sort so I didn’t have to worry about performance.


I started by instantiating the object from a TreeMap:

SortedMap<String,String> categories = new TreeMap<String,String>();

Since I am just storing the value as the key and the value I simply called the values() method on the SortedMap and iterated through the values:

Iterator iter = categories.values().iterator();

The result is a nicely sorted output!

Update:

From the comments you can see Loogan stateda Map is overkill and I totally agree. I was originally going to store an object in the map but eventually went down to just a String so when I first approached this I didn’t even consider a Set because I didn’t want to implement a Comparator in my class. Here is the updated code and thanks Loogan!

SortedSet categories = new TreeSet();
...
Iterator iter = categories.iterator();

If you want to learn more about hash maps and sortedmaps I scoured the internet for some really good references:

How HashMap works in Java

TreeMap vs HashMap

HashMap vs TreeMap

2 thoughts on “Sorting a HashMap in Java: SortedMap to the rescue!

    • Loogan, after looking at SortedSet you are correct! That is much more straightforward and much cleaner.

      I modified the code and it now looks very clean, thank you!


      SortedSet categories = new TreeSet();
      ...
      Iterator iter = categories.iterator();

      Like

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