我的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)
我想根据site_name
对list
进行排序。所以最终它会被排序为。
Apple, Banana, Cat
我试着这样做:
Collections.sort(l, new Comparator(){
public int compare(HashMap one, HashMap two) {
//what goes here?
}
});
发布于 2010-03-03 16:31:33
如果你让你的集合泛型,它最终会是这样的:
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
。但这与问题无关。)
发布于 2010-03-03 16:40:00
我认为现在是考虑重新设计的好时机。从您的示例中,看起来您的所有对象都有两个相同的字段- site_name
和site_code
。在这种情况下,为什么不定义自己的类而使用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);
}
}
然后你就可以使用Collections.sort()
了。
发布于 2010-03-03 16:31:45
类似于:
String codeOne = (String)one.get("site_code");
String codeTwo = (String)two.get("site_code");
return codeOne.compareTo(codeTwo);
我还没有编译或测试它,但它应该是这样的。
https://stackoverflow.com/questions/2373009
复制相似问题