views:

92

answers:

3

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?
           }
});
+4  A: 

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

Michael Myers
If I use this then I get a compilation error saying that I have not implemented all abstract methods. Trying to fix it automatically in NB it adds the following method along with the compare I already have: `public int compare(Object o1, Object o2) {throw new UnsupportedOperationException("Not supported yet.");}`
drake
@drake: Sorry about that, I forgot to add the generics to the Comparator definition. It should compile now.
Michael Myers
+3  A: 

Something like:

String codeOne = (String)one.get("site_code");
String codeTwo = (String)two.get("site_code");

return codeOne.compareTo(codeTwo);

I haven't compiled or tested this, but it should be along these lines.

Dick Chesterwood
(just beaten by mmyers - definitely go for their generics based answer).
Dick Chesterwood
+7  A: 

I think this is a great time to think about a redesign. From your example, it looks like all of your objects have the same two fields - site_name and site_code. In that case, why not define your own class rather than using a HashMap?

public class Site implements Comparable<Site> {
    private String site_name;
    private String site_code;

    // getters and setters, equals, and hashCode

    public int compareTo(Site other) {
        return this.site_name.compareTo(other.getSiteName);
    }
}

And then you can just use Collections.sort().

danben
+1 - This is absolutely the way to go.
Michael Myers