Problem in sorting using Comparator interface
I have created a ArrayList of HashMap like
ArrayList<HashMap<?,?>> var = new ArrayList<HashMap<?,?>>();
My HashMaps contains a String value "name" with key "name".What I want is to sort ArrayList by name so can I开发者_运维百科 do this using Comparator? Please Help Me.
ArrayList<HashMap<String,String>> var = new ArrayList<HashMap<String,String>>();
Collections.sort(var, new Comparator(){
public int compare(Object o1, Object o2)
{
Map map1 = (Map) o1;
Map map2 = (Map)o2;
String name1 = (String) map1.get("name");
String name2 = (String) map2.get("name");
if(name1 != null){
return name1.compareTo(name2);
} else if(name2 != null){
return name2.compareTo(name1);
}else{
return 0;
}
}
});
Here is the answer.
You could try something like this.
public int compare(Object o1, Object o2) {
String one = (String)((HashMap)o1).get("name");
String two = (String)((HashMap)o2).get("name");
return one.compareTo(two);
}
I haven't compiled this, so be sure to check its correct. =)
精彩评论