1

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.

2 Answers 2

3
        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.

Sign up to request clarification or add additional context in comments.

4 Comments

the use of Map (and not Map<T1,T2>) - without generics is deprecated. also note no null check for map1.get("name"). but besides from it - this will do the trick.
What i have written is just a template.
Oh I just realize we can do that. :)
@amit yes , i did that in the edit. So that anyone can try using the code directly.
1

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. =)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.