1

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?

Bitmap
  • 12,402
  • 16
  • 64
  • 91

4 Answers4

2

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
}
Bohemian
  • 412,405
  • 93
  • 575
  • 722
0

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)

Peter Lawrey
  • 525,659
  • 79
  • 751
  • 1,130
0

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

dimitrisli
  • 20,895
  • 12
  • 59
  • 63
0

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.

Jean Logeart
  • 52,687
  • 11
  • 83
  • 118