Java – how to sort hash map list

I have a HashMap list, as shown 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 want to be based on site_ Name sorts the list So in the end it will be classified as

Apple,Banana,Cat

I'm trying something like this:

Collections.sort(l,new Comparator(){
           public int compare(HashMap one,HashMap two) {
              //what goes here?
           }
});

Solution

If you make your collection generic, it will eventually look 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 cannot use generics because you are stuck on a 1.4 or earlier platform, you must convert get to string

(in addition, as a style, I prefer to declare variables as list and map rather than ArrayList and HashMap. But this has nothing to do with the problem.)

The content of this article comes from the network collection of netizens. It is used as a learning reference. The copyright belongs to the original author.
THE END
分享
二维码
< <上一篇
下一篇>>