Reputation: 12538
I have a List
of news feed with date attached, I want to walkthrough the list to determine which of the news feed's date is most current - and so I can arrange the news in the order of most current.
Any I deas how to achieve this?
Upvotes: 1
Views: 1697
Reputation: 425033
Sort the list using a Comparator based on the date of the item, then pick the first item using list.get(0).
Here's an compilable and runnable implementation:
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
}
Upvotes: 2
Reputation: 53829
Create a Comparator for the objects contained in your List
and then call the Collections.sort method with this List
to sort and the created Comparator
as parameters.
Upvotes: 0
Reputation: 21391
You can Collections.sort
your list of Feed
classes passing a Comparator
comparing to the dates that I am guessing are fields on your Feed
class
Upvotes: 0
Reputation: 533530
The most natural way would be to either sort the List e.g. sort in descending order using Collections.sort() with a custom comparator. Or use PriorityQueue and extract out the next new time each time (useful if say you only want the 10 most recent)
Upvotes: 0