0

I'm sorry if this is a duplicate, but I couldn't find a solution in posts I read.

I have a custom class, that contains few Strings and a Date. I made and ArrayList of this structure, and now, I want this ArrayList to be sorted from newest to oldest, using the Date field. How can I sort this list? Is there any way to build a custom comparator, that will sort ArrayList according to date in my class?

My class code:

public class ParsedWebData {

String title;
String url;
String description;
Date date;
String dateString;

public ParsedWebData() {

}

public ParsedWebData(String title, String url, String description, Date date, String dateString) {
    this.title = title;
    this.url = url;
    this.description = description;
    this.date = date;
    this.dateString = dateString;
}

public String getTitle() {
    return title;
}


public String getUrl() {
    return url;
}

public String getDescription() {
    return description;
}

public Date getDate() {return date;}

public String getDateString() {return dateString;}


}

So my arraylist declaration looks like that:

ArrayList<ParsedWebData> data = new ArrayList<>;

EDIT 1

I tried to use :

list.sort(Comparator.comparing(ParsedWebData::getDate));

But I get:

Call requires API level 24 (current min is 16): java.util.ArrayList#Sort
ikurek
  • 604
  • 11
  • 27

2 Answers2

1

Yes this can be done using a custom comparator:

data.sort(Comparator.comparing(ParsedWebData::getDate).reversed());

the reversed() call is to sort from newest to oldest rather than the natural order of oldest to newest.

Other solutions include:

  • Sort as you use the elements (data.stream().sorted(...))
  • Use a collection that sorts as you add
  • Extend Comparable if this is a natural ordering
sprinter
  • 27,148
  • 6
  • 47
  • 78
0

It would be easiest to use a SortedSet (ArrayList does not have sorting built in by default; TreeSet is the concrete implementation),and then pass a custom Comparator which just delegates to the date object.

So the TreeSet gets constructed as something like

set = new TreeSet<ParsedWebData>(new CustomComparator<ParsedWebData>());

And the key method of the custom Comparator is implemented as the below.

int compare(T o1, T o2) {
    return o1.date.compare(o2.date);
}
Richard Campbell
  • 3,591
  • 23
  • 18
  • An `ArrayList` can be sorted with [`Collections.sort`](https://docs.oracle.com/javase/8/docs/api/java/util/Collections.html#sort-java.util.List-java.util.Comparator-), or in Java 8 there is a [`List#sort`](https://docs.oracle.com/javase/8/docs/api/java/util/List.html#sort-java.util.Comparator-) method. Using a `TreeSet` would remove duplicates. – 4castle Sep 11 '16 at 01:38
  • I was looking at 7 documentation; you're right re List.sort. – Richard Campbell Sep 11 '16 at 01:40
  • Making the list a set changes its semantics: it would remove duplicates as well as sorting. – sprinter Sep 11 '16 at 01:44