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;
while(itr.hasNext()){
cnt++;
Map.Entry e=(Map.Entry)itr.next();
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();
if(value1.compareTo(value2)==0){
String word1=(String)e1.getKey();
String word2=(String)e2.getKey();
//Sort String in an alphabetical order
result=word1.compareToIgnoreCase(word2);
} else{
//Sort values in a descending order
result=value2.compareTo( value1 );
}
return result;
}
}
}
Thanks that was great help
thanks i really want it
thank you very much, I really appriciate the effort ,its work wonderful
Thanks v. much for a great piece of code!
Hi mrtextminer
you are excellent , appreciate your efforts
James
A tip for developers like me
Collections.sort(myArrayList, new MyComparator());
Collections.reverse(myArrayList);
would make sort in reverse order
Thanks
James
james_smith73@yahoo.com
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. 😦
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.
I sincerely appreciate your posting of this, it just helped me out tremendously. Cheers!
Hi,
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.
Thanks.
Awesome, man!!!!
Thanks, my friend. You saved my lot of time!
the code is not working i get compilation errors
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.
very very helpful..my hearty thanks to u