我有一个 List
的 HashMap
如下所示
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)
我想根据 site_name
对 list
进行排序。所以最后它会被排序为。
Apple, Banana, Cat
我正在尝试这样的事情:
Collections.sort(l, new Comparator(){
public int compare(HashMap one, HashMap two) {
//what goes here?
}
});
最佳答案
如果你让你的集合通用化,它最终会看起来像这样:
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"));
}
});
如果因为卡在 1.4 或更早的平台上而无法使用泛型,则必须将 get
转换为 String
。
(此外,作为风格问题,我更愿意将变量声明为 List
和 Map
而不是 ArrayList
和 HashMap
。但这与问题无关。)
关于java - 如何对 HashMap 列表进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/2373009/