2011-08-23 88 views
1

我有一个List新闻提要日期附加,我想浏览列表以确定哪些新闻提要的日期是最新的 - 所以我可以按照最新的顺序安排新闻。如何检查列表中的日期是否最新

任何我deas如何实现这一目标?

+0

日期如何存储? – smitec

+0

http://stackoverflow.com/questions/1814095/sorting-an-arraylist-of-contacts的副本 –

+0

Feed中的日期如何表示? –

回答

2

根据物品的日期使用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 
} 
0

最自然的方法是要么对列表进行排序例如使用Collections.sort()和自定义比较器按降序排序。或者使用的PriorityQueue每次提取出下一个新的时间(有用的,如果说你只是想最近10个)

0

您可以Collections.sortFeed类传递Comparator比较,我猜上是字段的日期列表您Feed

0

创建包含在你的List的对象Comparator,然后调用Collections.sort方法与此List进行排序,并创建Comparator作为参数。

相关问题