我有一张地图列表,其中我有两个类别“foo”和“bar”! 现在我的功能,我可以迭代它并按照foo排序:
public List<Map<String, Object>> makeAllSkillsMaps(List<Stuff> li) {
List<Map<String, Object>> l = new LinkedList<Map<String, Object>>();
List<Skill> w_l = li;
for (Stuff stuff : w_l) {
Map<String, Object> r_m = new HashMap<String, Object>();
r_m.put("ID", stuff.getID());
r_m.put("Bar", stuff.getBar());
r_m.put("Foo", stuff.getFoo());
l.add(r_m);
}
Comparator<Map<String, Object>> mapComparator = new Comparator<Map<String, Object>>() {
public int compare(Map<String, Object> m2, Map<String, Object> m1) {
return ((String) m1.get("Foo").toString()).compareTo((String) m2.get("Foo").toString());
}
};
l.sort(mapComparator);
return l;
}
有没有一种优雅的方法可以通过两个类别对它进行排序,所以我首先按Foo进行排序,然后按Bar:
Foo | Bar | ID
============================
A | 1 | 922
A | 2 | 726
B | 5 | 121
B | 98 | 654
G | 1 | 823
G | 7 | 324
答案 0 :(得分:0)
第二次检查时,我不知道你为什么要将toString()
的结果转换为String
。
public int compare(Map<String, Object> m2, Map<String, Object> m1) {
int cmp = m1.get("Foo").toString().compareTo(m2.get("Foo").toString());
if (cmp == 0) {
return m1.get("Bar").toString().compareTo(m2.get("Bar").toString());
}
return cmp;
}