Home > database >  how to sort on a string date on a collection of objects
how to sort on a string date on a collection of objects

Time:12-07

So I'm having trouble remembering the syntax. I have an List of objects I'm trying to sort based on the value of date. The object looks like this.

Public class someobject{
    private String author;
    private String createDate;
    private String subject;
    private String body;
    private String claimNumber;
    private String authoringDate;
}

I'm trying to sort on the createDate value. Something like

List<someObject> someObjectList = new ArrayList<>();

someObjectList.sort()

currently the way the strings are arriving for the createDate object is YYYY/MM/DD.

CodePudding user response:

Dates in the format YYYY/MM/DD may be correctly sorted as strings, ie lexicographically, so:

someObjectList.sort(Comparator.comparing(someobject::getCreateDate));

or, if you don't have a getter method for createDate:

someObjectList.sort(Comparator.comparing(o -> o.createDate));

CodePudding user response:

For getting the correct comparing result you have to convert String value from the field "creationDate" to Date or LocalDate than you have to make Comparator for instance like that:

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY/MM/DD");
someObjectList.sort(Comparator.comparingLong(ob -> formatter.parse(ob.createDate).get(ChronoField.EPOCH_DAY)));

or

DateTimeFormatter formatter = DateTimeFormatter.ofPattern("YYYY/MM/DD");
someObjectList.sort(Comparator.comparingLong(ob -> LocalDate.parse(ob.createDate, formatter).atStartOfDay(ZoneId.systemDefault()).toEpochSecond()));
  • Related