我已根据名称对数据进行了排序。但是当我要根据" date"对哈希映射的arraylist数据进行排序时,我不知道如何解决它。我按名称排序的方法如下。
protected ArrayList<HashMap<String, String>> setListOrderByName(ArrayList<HashMap<String, String>> menuItems2) {
Collections.sort(menuItems2, new Comparator<HashMap<String, String>>() {
public int compare(HashMap<String, String> mapping1,
HashMap<String, String> mapping2) {
return mapping1.get(KEY_NAME).compareTo(mapping2.get(KEY_NAME));
}
});
return menuItems2;
}
我已收到xml解析的数据。我们以字符串格式获取名称,日期,时间等。
答案 0 :(得分:6)
将字符串转换为日期然后进行比较
protected ArrayList<HashMap<String, String>>
setListOrderByName(ArrayList<HashMap<String, String>> menuItems2) {
Collections.sort(menuItems2, new Comparator<HashMap<String, String>>() {
DateFormat f = new SimpleDateFormat("dd/MM/yyyy '@'hh:mm a");//do determ
@Override
public int compare(HashMap<String, String> mapping1,
HashMap<String, String> mapping2) {
try {
return f.parse(mapping1.get(KEY_NAME)).compareTo(f.parse(mapping2.get(KEY_NAME)));
} catch (ParseException e) {
throw new IllegalArgumentException(e);
}
}
});
return menuItem2;
}
答案 1 :(得分:2)
此处基于字符串日期排序HashMap的示例
protected ArrayList<HashMap<String, String>> setListOrderByName(ArrayList<HashMap<String, String>> menuItems2) {
Collections.sort(menuItems2, new Comparator<HashMap<String, String>>() {
public int compare(HashMap<String, String> mapping1,
HashMap<String, String> mapping2) {
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
Date date1 = formatter.parse(mapping1.get(DATE));
DateFormat formatter = new SimpleDateFormat("yyyy-MM-dd'T'HH:mm:ssz");
Date date2 = formatter.parse(mapping2.get(DATE));
if(date1.after(date2)){
return mapping1.get(DATE);
}else{
return mapping2.get(DATE);
}
}
});
return menuItems2;
}