gpt4 book ai didi

java - 如何检查列表中的日期是否是最新的

转载 作者:行者123 更新时间:2023-11-30 04:59:53 25 4
gpt4 key购买 nike

我有一个附加了日期的新闻提要列表,我想浏览该列表以确定哪个新闻提要的日期是最新的 - 这样我就可以按最新的顺序排列新闻。

我知道如何实现这一目标吗?

最佳答案

使用 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
}

关于java - 如何检查列表中的日期是否是最新的,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7159611/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com