Sorting list of objects by date property

Spacejockey picture Spacejockey · Nov 29, 2018 · Viewed 11.6k times · Source

I have an object that contains two LocalDate properties:

public class SomeObject {
    private LocalDate startDate;
    private LocalDate endDate;
}

Constructor and stuff ommitted for brevity. I want to sort a list of these objects by their startdate and then assign the startdate of the next object to the previous object's enddate. To clarify, I start with a list of these objects:

SomeObject object1 = new SomeObject(LocalDate.parse("2015-01-01"), null);
SomeObject object2 = new SomeObject(LocalDate.parse("2014-01-01"), null);
SomeObject object3 = new SomeObject(LocalDate.parse("2016-01-01"), null);

List<SomeObject> list = Arrays.asList(object1, object2, object3);

And after sorting it should return this:

for (SomeObject object : list) {
    System.out.println(object.startDate.toString() + " " + object.endDate.toString() );
}

2014-01-01 2015-01-01
2015-01-01 2016-01-01
2016-01-01 null

Each list will only contain 3 or 4 of these objects at most, but the code might have to process tens of thousands of these lists, so I'm looking for an efficient way to do this.

Answer

Ralf Renz picture Ralf Renz · Nov 29, 2018

You can use Collections.sort with a Comparator. In Java 8 with Lambdas it looks like this:

    Collections.sort(list, (x, y) -> x.startDate.compareTo(y.startDate));

    for (int i = 0; i < (list.size() - 1); i++) {
        list.get(i).endDate = list.get(i + 1).startDate;
    }