这可能是一个旧响应,但我使用了这篇文章中的一些示例来创建一个比较器,该比较器将按列表中的一个对象(即时间戳)对HashMap<String, String> 中的ArrayList 进行排序。
我有这些物品:
ArrayList<Map<String, String>> alList = new ArrayList<Map<String, String>>();
地图对象如下:
Map<String, Object> map = new HashMap<>();
// of course this is the actual formatted date below in the timestamp
map.put("timestamp", "MM/dd/yyyy HH:mm:ss");
map.put("item1", "my text goes here");
map.put("item2", "my text goes here");
我使用该映射在循环中使用alList.add(map) 函数将所有对象加载到数组列表中。
现在,我创建了自己的比较器:
import org.joda.time.DateTime;
import org.joda.time.format.DateTimeFormat;
import org.joda.time.format.DateTimeFormatter;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.HashMap;
import java.util.Map;
public class DateSorter implements Comparator {
public int compare(Object firstObjToCompare, Object secondObjToCompare) {
String firstDateString = ((HashMap<String, String>) firstObjToCompare).get("timestamp");
String secondDateString = ((HashMap<String, String>) secondObjToCompare).get("timestamp");
if (secondDateString == null || firstDateString == null) {
return 0;
}
// Convert to Dates
DateTimeFormatter dtf = DateTimeFormat.forPattern("MM/dd/yyyy HH:mm:ss");
DateTime firstDate = dtf.parseDateTime(firstDateString);
DateTime secondDate = dtf.parseDateTime(secondDateString);
if (firstDate.isAfter(secondDate)) return -1;
else if (firstDate.isBefore(secondDate)) return 1;
else return 0;
}
}
我现在可以随时在数组上调用 Comparator,它会对我的数组进行排序,给我位置 0(列表顶部)的最新时间戳和列表末尾的最早时间戳。新帖子基本上都会放在首位。
Collections.sort(alList, new DateSorter());
这可能会对某人有所帮助,这就是我发布它的原因。考虑 compare() 函数中的返回语句。有 3 种类型的结果。如果它们相等则返回 0,如果第一个日期在第二个日期之前返回 >0,如果第一个日期在第二个日期之后返回