我有一个附有日期的新闻提要的List
,我想遍历列表以确定哪个新闻提要的日期是最新的,这样我就可以按最新的顺序排列新闻。
我知道如何做到这一点吗?
使用Comparator根据项目的日期对列表进行排序,然后使用list.get(0(.选择第一个项目
这里有一个可编译和可运行的实现:
static class NewsFeed {
String news;
Date date;
private NewsFeed(String news, Date date) {
this.news = news;
this.date = date;
}
public String getNews() {
return news;
}
public Date getDate() {
return date;
}
}
public static void main(String[] args) throws Exception {
List<NewsFeed> list = new ArrayList<NewsFeed>();
list.add(new NewsFeed("A", new Date(System.currentTimeMillis() - 1000)));
list.add(new NewsFeed("B", new Date())); // This one is the "latest"
list.add(new NewsFeed("C", new Date(System.currentTimeMillis() - 2000)));
Collections.sort(list, new Comparator<NewsFeed>() {
public int compare(NewsFeed arg0, NewsFeed arg1) {
// Compare in reverse order ie biggest first
return arg1.getDate().compareTo(arg0.getDate());
}
});
NewsFeed latestNewsFeed = list.get(0);
System.out.println(latestNewsFeed.getNews()); // Prints "B", as expected
}
最自然的方法是对List进行排序,例如使用Collections.sort((和自定义比较器按降序排序。或者使用PriorityQueue,每次提取下一个新时间(如果你只想要10个最近的时间,这很有用(
与我猜是Feed
类上字段的日期相比,您可以Collections.sort
您的Feed
类列表通过Comparator
为包含在List
中的对象创建一个Comparator,然后使用此List
调用Collections.sort方法进行排序,并将创建的Comparator
作为参数。