Sunday, February 26, 2012

Sorting a Map based on values


/**
 * The Class HashMapShortOnValue.
 */
class MapShortOnValue{

/**
* Gets the sorted result for hash map based on value.
*
* @return the sorted result for hash map based on value
*/
public static void getSortedResultForHashMapBasedOnValue(){
 Map<PersonObject, Object> map= new HashMap<PersonObject, Object>();
 map.put(new PersonObject("Abhi", 25), "Abhinav");
 map.put(new PersonObject("Bishu", 21), "Vivek");
 map.put(new PersonObject("Raj", 26), "Rahul");
 map.put(new PersonObject("Kunnu", 28), "Kunal");
 System.out.println("Unsorted hashMap: "+map);
     Map<PersonObject, Object> sortedMapOnVal=new TreeMap<PersonObject, Object>(new HashMapValueComparator(map));
     sortedMapOnVal.putAll(map);
     System.out.println("Sorted map based on values: "+sortedMapOnVal);
}
}

/**
 * The Class HashMapValueComparator.
 */
class HashMapValueComparator implements Comparator<Object>{

/** The map. */
Map<PersonObject, Object> map;

/**
* Instantiates a new hash map value comparator.
*/
HashMapValueComparator(){
super();
}

/**
* Instantiates a new hash map value comparator.
* @param map the map
*/
HashMapValueComparator(Map<PersonObject, Object> map){
super();
this.map=map;
}

/* (non-Javadoc)
* @see java.util.Comparator#compare(java.lang.Object, java.lang.Object)
*/
public int compare(Object o1, Object o2){
int retType;

Object v1=map.get(o1);
Object v2=map.get(o2);

if(v1 instanceof String && v2 instanceof String){
if(v1.toString().toLowerCase().hashCode()>v2.toString().toLowerCase().hashCode()){
retType=1;
}else if(v1.toString().toLowerCase().hashCode()<v2.toString().toLowerCase().hashCode()){
retType=-1;
}
else{
retType=0;
}
}else{
if(v1.hashCode()>v2.hashCode()){
retType=1;
}else if(v1.hashCode()<v2.hashCode()){
retType=-1;
}
else{
retType=0;
}
}
return retType;
}
}

/**
 * The Class Person.
 */
class PersonObject{
/** The age. */
int age;
/** The name. */
String name;

/**
* Instantiates a new person.
*/
PersonObject(){
super();
}

/**
* Instantiates a new person.
* @param name the name
* @param age the age
*/
PersonObject(String name,int age){
super();
this.name=name;
this.age=age;
}

/* (non-Javadoc)
* @see java.lang.Object#toString()
*/
public String toString(){
return name+" | "+age;
}

/* (non-Javadoc)
* @see java.lang.Object#equals(java.lang.Object)
*/
public boolean equals(Object o){
     PersonObject p=(PersonObject)o;
     return this.age==p.age && this.name.equals(p.name);
}
}

No comments:

Post a Comment

Thanks for your comments/Suggestions.