Sunday, February 26, 2012

Sorting a Map using map value


For sorting a java Map on values i have used Comparator. Here is the demonstration.

---------------------------------------------------------------------------------------------------------------
import java.util.Comparator; 
import java.util.HashMap; 
import java.util.Map; 
import java.util.TreeMap; 

public class SortMapOnValues

public static void main(String[] args){ 
Map<Developer,Object> map=new HashMap<Developer,Object>(); 
map.put(new Developer("abhi", 21, "Allahabad"), 101); 
map.put(new Developer("ashu", 24, "Kanpur"), 104); 
map.put(new Developer("mayank", 23, "Noida"), 102); 
map.put(new Developer("naveen", 27, "Lucknow"), 103); 
System.out.println("Unsorted map: "+map); 
ValComparator valComp=new ValComparator(map); 
Map<Developer,Object> sortedMap=new TreeMap<Developer,Object>(valComp); 
sortedMap.putAll(map); 
System.out.println("Sorted map on values: "+sortedMap); 



class ValComparator implements Comparator<Object>{ 
Map<Developer,Object> m; 
public ValComparator() { 
super(); 

public ValComparator(Map<Developer,Object> map) { 
super(); 
this.m=map; 

public int compare(Object o1, Object o2) { 
int sort; 
if(m.get(o1).hashCode()>m.get(o2).hashCode()){ 
sort=1; 
}else if(m.get(o1).hashCode()<m.get(o2).hashCode()){ 
sort=-1; 
}else{ 
sort=0; 

return sort; 




class Developer{ 

String name; 

int age; 

String address; 

public String toString(){ 
return "("+name+";"+age+";"+address+")"; 



public Developer(){ 
super(); 


public Developer(String name, int age, String address){ 
super(); 
this.name = name; 
this.age = age; 
this.address = address; 


@Override 
public int hashCode() { 
final int prime = 31; 
int result = 1; 
result = prime * result + ((address == null) ? 0 : address.hashCode()); 
result = prime * result + age; 
result = prime * result + ((name == null) ? 0 : name.hashCode()); 
return result; 


@Override 
public boolean equals(Object obj) { 
if (this == obj) 
return true; 
if (obj == null) 
return false; 
if (getClass() != obj.getClass()) 
return false; 
Developer other = (Developer) obj; 
if (address == null) { 
if (other.address != null) 
return false; 
} else if (!address.equals(other.address)) 
return false; 
if (age != other.age) 
return false; 
if (name == null) { 
if (other.name != null) 
return false; 
} else if (!name.equals(other.name)) 
return false; 
return true; 



Output:> 
Unsorted map: {(naveen;27;Lucknow)=103, (mayank;23;Noida)=102, (ashu;24;Kanpur)=104, (abhi;21;Allahabad)=101} 

Sorted map on values: {(abhi;21;Allahabad)=101, (mayank;23;Noida)=102, (naveen;27;Lucknow)=103, (ashu;24;Kanpur)=104}

No comments:

Post a Comment

Thanks for your comments/Suggestions.