Java Hashtable: Sorted by Values

When writing a program, we occasionally encounter a situation where we need to use Hashtable for storing data and then sort data in the Hashtable. In this blog, I demonstrate how to sort data in a Hashtable based on values.

Suppose that we need to count number of unique words in a text document and then sort those words in descending order based on their frequencies. If two words have the same frequency, they will be sorted in alphabetical order. So, we can use Hashtable where keys are unique words or String and values are frequencies or Integer.

There are two important things: 1) Create an inner (or ordinary) class that implements Comparator class and 2) Use Collections.sort() method for sorting. Here is a working source code.

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.Map;

public class Testing {

public static void main(String[] args) {

//Create a hashtable
Hashtable myhash=new Hashtable();

//Put things in Hashtable
myhash.put("AAB", 2);
myhash.put("ABC", 2);
myhash.put("AAX", 3);

//Put keys and values in to an arraylist using entryset
ArrayList myArrayList=new ArrayList(myhash.entrySet());

//Sort the values based on values first and then keys.
Collections.sort(myArrayList, new MyComparator());

//Show sorted results
Iterator itr=myArrayList.iterator();
String key="";
int value=0;
int cnt=0;

Map.Entry e=(Map.Entry);

key = (String)e.getKey();
value = ((Integer)e.getValue()).intValue();

System.out.println(key+”, “+value);


static class MyComparator implements Comparator{

public int compare(Object obj1, Object obj2){

int result=0;Map.Entry e1 = (Map.Entry)obj1 ;

Map.Entry e2 = (Map.Entry)obj2 ;//Sort based on values.

Integer value1 = (Integer)e1.getValue();
Integer value2 = (Integer)e2.getValue();


String word1=(String)e1.getKey();
String word2=(String)e2.getKey();

//Sort String in an alphabetical order

} else{
//Sort values in a descending order
result=value2.compareTo( value1 );

return result;



This entry was posted in Java. Bookmark the permalink.

15 Responses to Java Hashtable: Sorted by Values

  1. Anon says:

    Thanks that was great help

  2. sunil says:

    thank you very much, I really appriciate the effort ,its work wonderful

  3. Gert says:

    Thanks v. much for a great piece of code!

  4. Hi mrtextminer

    you are excellent , appreciate your efforts


  5. A tip says:

    A tip for developers like me

    Collections.sort(myArrayList, new MyComparator());


    would make sort in reverse order


  6. Marc_Hawke says:

    Thanks for that. I’ve done the custom Comparator route before and I didn’t want to have to do that again. Guess I have no choice.

    I’ve been researching this for some time now and yours is the most succinct way so far. It’s very annoying that it requires 6 included libraries, my HashTable has to migrate through 4 classes, and when I compile it’s going to create 2 new class files.

    meanwhile, the same answer in Perl:

    ( sort { $hash{$a} cmp $hash{$b} } keys %hash )

    So sad. 😦

  7. Marc_Hawke says:

    It’s me again Margaret.

    Just wanted to say that in spite of my negativity in the first post, this was how I ended up doing it. Thanks for the help.

  8. Brian says:

    I sincerely appreciate your posting of this, it just helped me out tremendously. Cheers!

  9. Sam says:


    It was a nice code. I was totally stuck, bcoz i was not able 2 solve the prob of sorting hastable based on the values.

    Sincerely nice code. Good work.


  10. Bikash Gyawali says:

    Thanks, my friend. You saved my lot of time!

  11. sundar says:

    the code is not working i get compilation errors

    • mrtextminer says:

      Please check your syntax or using any IDE for your program. Your errors might be caused by differences of double quotes between in the Web site and in Java language.

  12. keerthie says:

    very very hearty thanks to u

Leave a Reply

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

You are commenting using your 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