简体   繁体   English

如何排序哈希映射列表

[英]how to sort list of hashmaps

I have a List of HashMap such as below 我有一个HashMap List ,如下所示

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 . 我想基于site_namelist进行排序。 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?
           }
});

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 . 如果由于你被困在1.4或更早版本的平台上而无法使用泛型,那么你必须将getString

(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.) (另外,作为一种风格,我更喜欢将变量声明为ListMap而不是ArrayListHashMap 。但这与问题无关。)

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 . 从您的示例中,看起来所有对象都具有相同的两个字段 - site_namesite_code In that case, why not define your own class rather than using a HashMap ? 在这种情况下,为什么不定义自己的类而不是使用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() . 然后你可以使用Collections.sort()

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. 我没有编译或测试过这个,但它应该沿着这些方向。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM