DEV Community

loading...

How to Sort Java List Objects by Date property with Examples

loizenai profile image loizenai ・2 min read

https://grokonez.com/java/how-to-sort-java-list-objects-by-date-property-with-examples

How to Sort Java List Objects by Date property with Examples

[no_toc]
In the tutorial, We discuss how to Sort Java List Objects by Date property with difference Date types: java.util.Date(using SimpleDateFormat), LocalDate, LocalDateTime. Java provides 2 main approaches for sorting Java List with Comparator:

  • java.util.Collections.sort(List list, Comparator super Customer> c): sorting the specified list according to the order providing by the specified comparator.
  • java.util.Collection.stream().sorted(Comparator super T> comparator): returning a stream consisting of the elements of this stream, sorted according to the provided Comparator.

Let's do more details with Java syntax examples (Java 7 and Java 8) by descending and ascending sorting order.

Sorting with Collections.sort()

For sorting a Java List with Objects, we use Collections.sort() API:


public static  void sort(List list, Comparator super T> c) {
    list.sort(c);
}
  • Sorts the specified list according to the order induced by the specified comparator.
  • According to Oracle: "This implementation is a stable, adaptive, iterative mergesort that requires far fewer than n lg(n) comparisons when the input array is partially sorted, while offering the performance of a traditional mergesort when the input array is randomly ordered. If the input array is nearly sorted, the implementation requires approximately n comparisons. Temporary storage requirements vary from a small constant for nearly sorted input arrays to n/2 object references for randomly ordered input arrays."

Exception:

  • ClassCastException - if the list contains elements that are not mutually comparable using the specified comparator.
  • UnsupportedOperationException - if the specified list's list-iterator does not support the set operation.
  • IllegalArgumentException - (optional) if the comparator is found to violate the Comparator contract

    Sorting Java Objects Examples by java.util.Date property

    We create a Java Class Object that has a birthday property with java.util.Date type as below:

More at:

https://grokonez.com/java/how-to-sort-java-list-objects-by-date-property-with-examples

How to Sort Java List Objects by Date property with Examples

Discussion (0)

pic
Editor guide