makapaka
makapaka

Reputation: 179

Sorting Java List of objects using string date

I know there are lots of posts out there on sorting lists/arrays etc, but I'm a bit confused as to the best way of doing it. My list of objects also contains a date field - but that date is stored as a string, so do I need to convert them all first and then sort, or is there a way to sort the objects in the list using this parameter without first converting them?

So basically the list:

List<NewsFeed> newslist;

The NewsFeed object:

String title;
String description;
String URL;
String date;

Date looks something like:

Fri Dec 26 23:00:00 AEDT 2014

Upvotes: 1

Views: 4661

Answers (4)

Tkachuk_Evgen
Tkachuk_Evgen

Reputation: 1354

Use this

Collections.sort(newsList, new Comparator<NewsFeed>() {
        DateFormat f = new SimpleDateFormat("dd/MM/yyyy");//or your pattern
        @Override
        public int compare(NewsFeed o1, NewsFeed o2) {
            try {
                return f.parse(o1.getDate()).compareTo(f.parse(o2.getDate()));
            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }
        }
    });

With Comparable it looks like this:

   public class NewsFeed implements Comparable<NewsFeed>{
        //your fields and getters/setters
        private DateFormat f = new SimpleDateFormat("dd/MM/yyyy");//or your pattern
        @Override
        public int compareTo(NewsFeed o) {
            try {
                return f.parse(this.getDate()).compareTo(f.parse(o.getDate()));
            } catch (ParseException e) {
                throw new IllegalArgumentException(e);
            }
       }
}

Upvotes: 2

TayTay
TayTay

Reputation: 7170

If you can't just store the dates as Date objects, you need to define a custom comparator (that will end up implicitly converting the Strings to Date objects, so you really may as well just store them as dates). You can define both of these as fields in your class:

private final static String dateFormat = "EEE MMM dd HH:mm:ss yyyy";
private final static Comparator<String> dateComp = new Comparator<String>() {
        public int compare(String s1, String s2) {
            Date d1 = null;
            try {
                d1 = new SimpleDateFormat( dateFormat,Locale.ENGLISH ).parse(s1);
            } catch (ParseException e) {
                //HANDLE THIS EXCEPTION
            }

            Date d2 = null;
            try {
                d2 = new SimpleDateFormat( dateFormat,Locale.ENGLISH ).parse(s2);
            } catch (ParseException e) {
                //HANDLE THIS EXCEPTION
            }
            return d1.compareTo(d2);
        }
    };

Of course, you will have to effectively handle the required try/catch blocks and potential parsing exceptions. Additionally, you will have be to certain that is the format of your incoming date strings.

Here is an example using the above comparator:

    String[] dateArray = new String[] {"Sat Dec 27 23:00:00 2014","Fri Dec 26 23:00:00 2014","Sun Dec 28 23:00:00 2014"};
    List<String> dateList = new ArrayList<String>(Arrays.asList(dateArray));
    Collections.sort(dateList, dateComp);

Prints:

[Fri Dec 26 23:00:00 2014, Sat Dec 27 23:00:00 2014, Sun Dec 28 23:00:00 2014]

Upvotes: 0

Steven Weng
Steven Weng

Reputation: 322

Your class NewsFeed have to implement Comparable interface and @override compareTo method to define your sort rule. Then use Arrays.sort method to sort your newslist.

class NewsFeed implements Comparable<NewsFeed>{
    //members
    @Override
    public int compareTo(NewsFeed o) {
        // TODO Your sort rule
        return 0;
    }

}

List<NewsFeed> newslist;
...
Arrays.sort(newslist);

Upvotes: 2

GreyBeardedGeek
GreyBeardedGeek

Reputation: 30088

Convert the string to a date as you read the RSS, and store it as a Date in your NewsFeed object. Then you can implement the Comparable interface and delegate to the date.

Any answer that has you converting the date I'm the compareTo method will be doing an unnecessarily large number of conversions.

Upvotes: 0

Related Questions