1

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
skuntsel
  • 11,624
  • 11
  • 44
  • 67
makapaka
  • 169
  • 5
  • 16
  • 2
    "but that date is stored as a String" <-- why? Can't you store is as an actual date instead? – fge Dec 26 '14 at 13:18
  • Are you pulling this list of objects from the database? If so, you can build your query to sort them very easily. – Tamby Kojak Dec 26 '14 at 13:18
  • take a look at [how to sort Date which is in string format in java](http://stackoverflow.com/questions/14451976/how-to-sort-date-which-is-in-string-format-in-java) – Tkachuk_Evgen Dec 26 '14 at 13:22
  • @Tkachuk_Evgen To convert that answer for my List - do I simply nest it inside a foreach type loop ? thx for the link. Otherwise, the list is coming from RSS feed - thats why each member is String but yes obviously i can convert it – makapaka Dec 26 '14 at 13:36

4 Answers4

2

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);
            }
       }
}
Tkachuk_Evgen
  • 1,334
  • 11
  • 17
  • if i use the Comparable interface, what do I compare within the compareTo method ? which dates do I compare ? Looking at this example http://www.javamex.com/tutorials/collections/sorting_comparable_compareto.shtml it is passing in something to compare - but how do i compare a List ? thx – makapaka Dec 26 '14 at 14:22
  • I am so grateful, that is perfect, thank you i wish i could award a million points for sticking with me ! :) – makapaka Dec 26 '14 at 14:40
  • Hey, I am trying the same thing, but my date doesn't contain time It's of the format yyyy-MM-dd only. When I try to sort with the above method, it's not working. How can I sort the list? – Aradhna Sep 27 '17 at 18:53
  • @Tkachuk_Evgen I did. But still it is not sorting the list. – Aradhna Sep 27 '17 at 20:50
2

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);
Steven Weng
  • 322
  • 1
  • 9
  • thx i like this idea - but having never used the comparable interface, within the compareTo method, what am I comparing in the List sense - I'm not getting my head around this conceptually. Meanwhile I will research this Comparable usage , thx ;) – makapaka Dec 26 '14 at 14:05
  • There have some example [http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/](http://www.mkyong.com/java/java-object-sorting-example-comparable-and-comparator/) – Steven Weng Dec 26 '14 at 14:17
0

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.

GreyBeardedGeek
  • 29,460
  • 2
  • 47
  • 67
0

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]
TayTay
  • 6,882
  • 4
  • 44
  • 65