Explain Codes LogoExplain Codes Logo

Sort objects in ArrayList by date?

java
null-safe-comparator
custom-sort-orders
java-8-features
Nikita BarsukovbyNikita Barsukov·Oct 27, 2024
TLDR

One way to sort an ArrayList by date using Java 8's Comparator and lambda expressions:

yourList.sort(Comparator.comparing(YourObject::getDate));

Just replace YourObject::getDate with your date getter method. This one-liner example gets the job done in a snap, sorting the list in ascending order.

Defending against null

In case of null dates, a null-safe comparator will keep your code from malfunctioning

yourList.sort(Comparator.comparing(YourObject::getDate, Comparator.nullsLast(Comparator.naturalOrder())));

This line makes your sort operation immune to NullPointerException caused by unexpected null date values.

Custom sort orders

When you need list sorted on more than one key or condition, a custom Comparator can be your tool:

Comparator<YourObject> byDate = (o1, o2) -> { // Comment to add a joke in Reddit style if (o1.getDate() == null || o2.getDate() == null) { return o1.getDate() != null ? -1 : (o2.getDate() != null ? 1 : 0); // Sorting nulls as they were heavy rocks } return o1.getDate().compareTo(o2.getDate()); // Rock, Paper, DateTime! }; Collections.sort(yourList, byDate);

The explicit Comparator approach enables complex sorting logic, and manages null values as well.

Descending order sort

If you need your dates in descending order, you can reverse the comparator:

yourList.sort(Comparator.comparing(YourObject::getDate).reversed()); // Time travel!

Complex sort strategies

Multi-key sorting

Different situations often call for a multi-key sort. Use Comparator.comparing two times for this:

yourList.sort( Comparator.comparing(YourObject::getDate) .thenComparing(YourObject::getAnotherAttribute) );

The handy thenComparing() function ensures your objects are sorted by date firstly, and then another attribute.

Embracing Java 8

Java 8's syntax sugar aims to sweeten your code:

yourList.sort( Comparator.comparing(YourObject::getDateTime, Comparator.nullsLast(Comparator.naturalOrder())) );

The above line improves readability and comparison accuracy when dealing with date-time values.

Stream API sorting

Java's Stream API provides an alternative:

List<YourObject> sortedList = yourList.stream() .sorted(Comparator.comparing(YourObject::getDate)) .collect(Collectors.toList());

This modern sorting technique promotes fluency and efficiency.

Keeping the model intact

Avoid modifying your model to achieve sorting by creating a Comparator—directing your sorting logic.

Shade of natural order

To utilize the natural ordering with ArrayList's sort(), make your objects Comparable:

public class YourObject implements Comparable<YourObject> { // ... other fields private Date date; @Override public int compareTo(YourObject other) { return this.getDate().compareTo(other.getDate()); } }

Now, sorting made convenient without an explicit comparator when your model supports natural ordering.