Thursday, July 21, 2011

Hashtable data sorting based on Value. Hash table sorting, Java Hashtable: Sorted by Values

package com.test;

import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.Hashtable;
import java.util.Iterator;
import java.util.LinkedHashMap;
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("Z", "H");
myhash.put("B", "P");
myhash.put("C", "R");
myhash.put("D", "A");
myhash.put("M", "B");
myhash.put("P", "D");

//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="";
String value;
int cnt=0;
LinkedHashMap linkedmap = new LinkedHashMap();
while(itr.hasNext()){

cnt++;
Map.Entry e=(Map.Entry)itr.next();

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

System.out.println(key+","+value);

linkedmap.put(key, value);

}

System.out.println(linkedmap);

}// end of method

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.

String value1 = (String)e1.getValue();
String value2 = (String)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=value1.compareTo( value2 );
}

return result;
}

}

}


-------------------------------------
Result :
D,A
M,B
P,D
Z,H
B,P
C,R
{D=A, M=B, P=D, Z=H, B=P, C=R}

No comments:

Post a Comment

Followers