Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

how to sort list of hashmaps

I have a List of HashMap such as below

ArrayList l = new ArrayList ();
HashMap m = new HashMap ();
m.add("site_code","AL");
m.add("site_name","Apple");
l.add(m);
m = new HashMap();
m.add("site_code","JL");
m.add("site_name","Cat");
l.add(m);
m = new HashMap();
m.add("site_code","PL");
m.add("site_name","Banana");
l.add(m)

I'd like to sort the list based on site_name. So in the end it would be sorted as.

Apple, Banana, Cat

I was trying something like this:

Collections.sort(l, new Comparator(){
           public int compare(HashMap one, HashMap two) {
              //what goes here?
           }
});
like image 517
drake Avatar asked Nov 27 '22 23:11

drake


1 Answers

If you make your collections generic, it will end up looking about like this:

Collections.sort(l, new Comparator<HashMap<String, String>>(){ 
        public int compare(HashMap<String, String> one, HashMap<String, String> two) { 
            return one.get("site_name").compareTo(two.get("site_name"));
        } 
});

If you can't use generics because you're stuck on a 1.4 or earlier platform, then you'll have to cast the get's to String.

(Also, as a matter of style, I'd prefer declaring the variables as List and Map rather than ArrayList and HashMap. But that's not relevant to the question.)

like image 124
Michael Myers Avatar answered Dec 09 '22 20:12

Michael Myers