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
: sorting the specified list according to the order providing by the specified comparator.list, Comparator super Customer> c) 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 <T> void sort(List<T> 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:
import java.text.SimpleDateFormat; import java.util.Date; class Customer { private int id; private String name; private Date birthday; public Customer(int id, String name, Date birthday){ this.id = id; this.name = name; this.birthday = birthday; } public int getId() { return id; } public Date getBirthday() { return this.birthday; } public String toString() { return String.format("id = %d, name = %s, birthday = %s", this.id, this.name, this.birthday.toString()); } } |
– Create a List of Customer as below:
List<Customer> customers = Arrays.asList( new Customer(1, "Jack", new SimpleDateFormat("dd-MM-yyyy").parse("23-04-1989")), new Customer(7, "Mary", new SimpleDateFormat("dd-MM-yyyy").parse("19-08-1977")), new Customer(3, "Joe", new SimpleDateFormat("dd-MM-yyyy").parse("09-02-1980")), new Customer(9, "Peter", new SimpleDateFormat("dd-MM-yyyy").parse("18-07-1983")), new Customer(2, "Bob", new SimpleDateFormat("dd-MM-yyyy").parse("15-10-1978")), new Customer(5, "Jane", new SimpleDateFormat("dd-MM-yyyy").parse("19-08-1977")) ); |
– Let’s do sorting!
Define a Sorting Comparator
Create a Comparator with Customer class, in compare
function, we get time
of Date
to compare them:
Comparator<Customer> byBirthday = new Comparator<Customer>() { public int compare(Customer c1, Customer c2) { return Long.valueOf(c1.getBirthday().getTime()).compareTo(c2.getBirthday().getTime()); } }; |
– Full Example:
package com.grokonez.sortarray; import java.text.ParseException; import java.text.SimpleDateFormat; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.Date; import java.util.List; class Customer { private int id; private String name; private Date birthday; public Customer(int id, String name, Date birthday){ this.id = id; this.name = name; this.birthday = birthday; } public int getId() { return id; } public Date getBirthday() { return this.birthday; } public String toString() { return String.format("id = %d, name = %s, birthday = %s", this.id, this.name, this.birthday.toString()); } } /** * * JavaArraySortingExample * @author grokonez.com * */ public class JavaArraySortingExample { public static void main(String[] args) throws ParseException { List<Customer> customers = Arrays.asList( new Customer(1, "Jack", new SimpleDateFormat("dd-MM-yyyy").parse("23-04-1989")), new Customer(7, "Mary", new SimpleDateFormat("dd-MM-yyyy").parse("19-08-1977")), new Customer(3, "Joe", new SimpleDateFormat("dd-MM-yyyy").parse("09-02-1980")), new Customer(9, "Peter", new SimpleDateFormat("dd-MM-yyyy").parse("18-07-1983")), new Customer(2, "Bob", new SimpleDateFormat("dd-MM-yyyy").parse("15-10-1978")), new Customer(5, "Jane", new SimpleDateFormat("dd-MM-yyyy").parse("19-08-1977")) ); Comparator<Customer> byBirthday = new Comparator<Customer>() { public int compare(Customer c1, Customer c2) { return Long.valueOf(c1.getBirthday().getTime()).compareTo(c2.getBirthday().getTime()); } }; Collections.sort(customers, byBirthday); for(int i=0; i<customers.size(); i++) { System.out.println(customers.get(i)); } } } |
– Output:
id = 7, name = Mary, birthday = Fri Aug 19 00:00:00 GMT+07:00 1977 id = 5, name = Jane, birthday = Fri Aug 19 00:00:00 GMT+07:00 1977 id = 2, name = Bob, birthday = Sun Oct 15 00:00:00 GMT+07:00 1978 id = 3, name = Joe, birthday = Sat Feb 09 00:00:00 GMT+07:00 1980 id = 9, name = Peter, birthday = Mon Jul 18 00:00:00 GMT+07:00 1983 id = 1, name = Jack, birthday = Sun Apr 23 00:00:00 GMT+07:00 1989 |
* We also can re-implemetation by using Anonymous Comparator Inner Class:
Collections.sort(customers, new Comparator<Customer>() { public int compare(Customer c1, Customer c2) { return Long.valueOf(c1.getBirthday().getTime()).compareTo(c2.getBirthday().getTime()); } }); |
Implement with Java 8 Lamda Expression
With the powerful of Lamda Expression, We can implement the Sorting Java Object List with Java 8 by Date Property more simply:
Collections.sort(customers, (c1, c2) -> { return Long.valueOf(c1.getBirthday().getTime()).compareTo(c2.getBirthday().getTime()); }); |
Note: We recommend to use the implementation with Java 8 Lamda Expression for more simple, readability.
Sorting Java Objects Examples by java.time.LocalDate property
We create a Java Class Object that has a birthday
property with java.time.LocalDate
type as below:
import java.time.LocalDate; import java.time.Month; import java.util.Arrays; import java.util.Comparator; class Customer { private int id; private String name; private LocalDate birthday; public Customer(int id, String name, LocalDate birthday){ this.id = id; this.name = name; this.birthday = birthday; } public int getId() { return id; } public LocalDate getBirthDay() { return this.birthday; } public String toString() { return String.format("id = %d, name = %s, birthday = %s", this.id, this.name, this.birthday.toString()); } } |
– Create a List of Customer as below:
Customer[] customers = new Customer[] { new Customer(1, "Jack", LocalDate.of(1989, Month.APRIL, 23)), new Customer(7, "Mary", LocalDate.of(1977, Month.AUGUST, 19)), new Customer(3, "Joe", LocalDate.of(1980, Month.FEBRUARY, 9)), new Customer(9, "Peter", LocalDate.of(1983, Month.JULY, 18)), new Customer(2, "Bob", LocalDate.of(1978, Month.OCTOBER, 15)), new Customer(5, "Jane", LocalDate.of(1977, Month.AUGUST, 19)) }; |
Define a Sorting Comparator
Create a Comparator with Customer class, in compare
function, we get time
of LocalDate
to compare them:
Comparator<Customer> byBirthday = new Comparator<Customer>() { public int compare(Customer c1, Customer c2) { if (c1.getBirthDay().isBefore(c2.getBirthDay())) return -1; else return 1; } }; |
– Full Example:
package com.grokonez.sortarray; import java.time.LocalDate; import java.time.Month; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; class Customer { private int id; private String name; private LocalDate birthday; public Customer(int id, String name, LocalDate birthday){ this.id = id; this.name = name; this.birthday = birthday; } public int getId() { return id; } public LocalDate getBirthDay() { return this.birthday; } public String toString() { return String.format("id = %d, name = %s, birthday = %s", this.id, this.name, this.birthday.toString()); } } public class JavaArraySortingExample { public static void main(String[] args) { List<Customer> customers = Arrays.asList( new Customer(1, "Jack", LocalDate.of(1989, Month.APRIL, 23)), new Customer(7, "Mary", LocalDate.of(1977, Month.AUGUST, 19)), new Customer(3, "Joe", LocalDate.of(1980, Month.FEBRUARY, 9)), new Customer(9, "Peter", LocalDate.of(1983, Month.JULY, 18)), new Customer(2, "Bob", LocalDate.of(1978, Month.OCTOBER, 15)), new Customer(5, "Jane", LocalDate.of(1977, Month.AUGUST, 19)) ); Comparator<Customer> byBirthday = new Comparator<Customer>() { public int compare(Customer c1, Customer c2) { if (c1.getBirthDay().isBefore(c2.getBirthDay())) return -1; else return 1; } }; // Sorting Collections.sort(customers, byBirthday); for(int i=0; i<customers.size(); i++) { System.out.println(customers.get(i)); } } } |
-> Output:
id = 7, name = Mary, birthday = 1977-08-19 id = 5, name = Jane, birthday = 1977-08-19 id = 2, name = Bob, birthday = 1978-10-15 id = 3, name = Joe, birthday = 1980-02-09 id = 9, name = Peter, birthday = 1983-07-18 id = 1, name = Jack, birthday = 1989-04-23 |
– We also can re-implemetation by using Anonymous Comparator Inner Class:
// Sorting Collections.sort(customers, new Comparator<Customer>() { @Override public int compare(Customer c1, Customer c2) { if (c1.getBirthDay().isBefore(c2.getBirthDay())) return -1; else return 1; } }); |
Implement with Java 8 Lamda Expression
We implement a simple solution with Java 8 Lamda Express:
// Sorting Collections.sort(customers, (c1, c2) -> { if (c1.getBirthDay().isBefore(c2.getBirthDay())) return -1; else return 1; }); |
Sorting Java Objects Examples by java.time.LocalDateTime property
With LocalDateTime
property type, We do the sorting as the same way with LocalDate
.
– Full Example with Java 8 Lamda Expression:
package com.grokonez.sortarray; import java.time.LocalDateTime; import java.time.Month; import java.util.Arrays; import java.util.Collections; import java.util.List; class Customer { private int id; private String name; private LocalDateTime orderTime; public Customer(int id, String name, LocalDateTime orderTime){ this.id = id; this.name = name; this.orderTime = orderTime; } public int getId() { return id; } public LocalDateTime getOrderTime() { return this.orderTime; } public String toString() { return String.format("id = %d, name = %s, birthday = %s", this.id, this.name, this.orderTime.toString()); } } /** * * JavaArraySortingExample * @author grokonez.com * */ public class JavaArraySortingExample { public static void main(String[] args) { List<Customer> customers = Arrays.asList( new Customer(1, "Jack", LocalDateTime.of(2019, Month.FEBRUARY, 27, 8, 30)), new Customer(7, "Mary", LocalDateTime.of(2019, Month.JANUARY, 27, 9, 21)), new Customer(3, "Joe", LocalDateTime.of(2019, Month.FEBRUARY, 27, 8, 40)), new Customer(9, "Peter", LocalDateTime.of(2019, Month.FEBRUARY, 1, 10, 11)), new Customer(2, "Bob", LocalDateTime.of(2019, Month.FEBRUARY, 1, 10, 11)), new Customer(5, "Jane", LocalDateTime.of(2019, Month.FEBRUARY, 24, 12, 04)) ); Collections.sort(customers, (c1, c2) -> { if (c1.getOrderTime().isBefore(c2.getOrderTime())) return -1; else return 1; }); for(int i=0; i<customers.size(); i++) { System.out.println(customers.get(i)); } } } |
– Output:
id = 7, name = Mary, birthday = 2019-01-27T09:21 id = 9, name = Peter, birthday = 2019-02-01T10:11 id = 2, name = Bob, birthday = 2019-02-01T10:11 id = 5, name = Jane, birthday = 2019-02-24T12:04 id = 1, name = Jack, birthday = 2019-02-27T08:30 id = 3, name = Joe, birthday = 2019-02-27T08:40 |
Descending Sorting with Collections.sort()
For descending sorting with Java list objects, We have 2 approaches:
– Modify Comparator for descending comparing order
– Or use reversed()
function of comparator – Recommended
Let’s do examples with LocalDateTime
:
Descending Sorting by Modify Comparator
We use isAfter()
function to re-define the Comparator with descending comparing, then do sorting:
Comparator<Customer> byOrderTime = (c1, c2) -> { if (c1.getOrderTime().isAfter(c2.getOrderTime())) return -1; else return 1; }; Collections.sort(customers, byOrderTime); |
– Full example:
package com.grokonez.sortarray; import java.time.LocalDateTime; import java.time.Month; import java.util.Arrays; import java.util.Collections; import java.util.Comparator; import java.util.List; class Customer { private int id; private String name; private LocalDateTime orderTime; public Customer(int id, String name, LocalDateTime orderTime){ this.id = id; this.name = name; this.orderTime = orderTime; } public int getId() { return id; } public LocalDateTime getOrderTime() { return this.orderTime; } public String toString() { return String.format("id = %d, name = %s, birthday = %s", this.id, this.name, this.orderTime.toString()); } } /** * * JavaArraySortingExample * @author grokonez.com * */ public class JavaArraySortingExample { public static void main(String[] args) { List<Customer> customers = Arrays.asList( new Customer(1, "Jack", LocalDateTime.of(2019, Month.FEBRUARY, 27, 8, 30)), new Customer(7, "Mary", LocalDateTime.of(2019, Month.JANUARY, 27, 9, 21)), new Customer(3, "Joe", LocalDateTime.of(2019, Month.FEBRUARY, 27, 8, 40)), new Customer(9, "Peter", LocalDateTime.of(2019, Month.FEBRUARY, 1, 10, 11)), new Customer(2, "Bob", LocalDateTime.of(2019, Month.FEBRUARY, 1, 10, 11)), new Customer(5, "Jane", LocalDateTime.of(2019, Month.FEBRUARY, 24, 12, 04)) ); Comparator<Customer> byOrderTime = (c1, c2) -> { if (c1.getOrderTime().isAfter(c2.getOrderTime())) return -1; else return 1; }; Collections.sort(customers, byOrderTime); for(int i=0; i<customers.size(); i++) { System.out.println(customers.get(i)); } } } |
-> Output:
id = 3, name = Joe, birthday = 2019-02-27T08:40 id = 1, name = Jack, birthday = 2019-02-27T08:30 id = 5, name = Jane, birthday = 2019-02-24T12:04 id = 9, name = Peter, birthday = 2019-02-01T10:11 id = 2, name = Bob, birthday = 2019-02-01T10:11 id = 7, name = Mary, birthday = 2019-01-27T09:21 |
Use reversed() function of Comparator
We do NOT modify the comparator But using reversed()
function for descending sorting:
Comparator<Customer> byOrderTime = (c1, c2) -> { if (c1.getOrderTime().isBefore(c2.getOrderTime())) return -1; else return 1; }; Collections.sort(customers, byOrderTime.reversed()); |
– Full example:
package com.grokonez.sortarray; ... class Customer { ... } /** * * JavaArraySortingExample * @author grokonez.com * */ public class JavaArraySortingExample { public static void main(String[] args) { List<Customer> customers = Arrays.asList( new Customer(1, "Jack", LocalDateTime.of(2019, Month.FEBRUARY, 27, 8, 30)), new Customer(7, "Mary", LocalDateTime.of(2019, Month.JANUARY, 27, 9, 21)), new Customer(3, "Joe", LocalDateTime.of(2019, Month.FEBRUARY, 27, 8, 40)), new Customer(9, "Peter", LocalDateTime.of(2019, Month.FEBRUARY, 1, 10, 11)), new Customer(2, "Bob", LocalDateTime.of(2019, Month.FEBRUARY, 1, 10, 11)), new Customer(5, "Jane", LocalDateTime.of(2019, Month.FEBRUARY, 24, 12, 04)) ); Comparator<Customer> byOrderTime = (c1, c2) -> { if (c1.getOrderTime().isBefore(c2.getOrderTime())) return -1; else return 1; }; Collections.sort(customers, byOrderTime.reversed()); for(int i=0; i<customers.size(); i++) { System.out.println(customers.get(i)); } } } |
-> Output:
id = 3, name = Joe, birthday = 2019-02-27T08:40 id = 1, name = Jack, birthday = 2019-02-27T08:30 id = 5, name = Jane, birthday = 2019-02-24T12:04 id = 9, name = Peter, birthday = 2019-02-01T10:11 id = 2, name = Bob, birthday = 2019-02-01T10:11 id = 7, name = Mary, birthday = 2019-01-27T09:21 |
Sorting Java Object List by Date property with Collection.stream()
Java 8 provides Stream
with new APIs for sorting List:
java.util.stream.Stream.sorted(Comparator<? super T> comparator) |
-> It returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.
With the powerful of stream, We can use it to create a new sorted List:
Comparator<Customer> byOrderTime = (c1, c2) -> { if (c1.getOrderTime().isBefore(c2.getOrderTime())) return -1; else return 1; }; List<Customer> newCustomers = customers.stream().sorted(byOrderTime.reversed()) .collect(Collectors.toList()); |
-> Full Example:
package com.grokonez.sortarray; import java.time.LocalDateTime; import java.time.Month; import java.util.Arrays; import java.util.Comparator; import java.util.List; import java.util.stream.Collectors; class Customer { private int id; private String name; private LocalDateTime orderTime; public Customer(int id, String name, LocalDateTime orderTime){ this.id = id; this.name = name; this.orderTime = orderTime; } public int getId() { return id; } public LocalDateTime getOrderTime() { return this.orderTime; } public String toString() { return String.format("id = %d, name = %s, birthday = %s", this.id, this.name, this.orderTime.toString()); } } /** * * JavaArraySortingExample * @author grokonez.com * */ public class JavaArraySortingExample { public static void main(String[] args) { List<Customer> customers = Arrays.asList( new Customer(1, "Jack", LocalDateTime.of(2019, Month.FEBRUARY, 27, 8, 30)), new Customer(7, "Mary", LocalDateTime.of(2019, Month.JANUARY, 27, 9, 21)), new Customer(3, "Joe", LocalDateTime.of(2019, Month.FEBRUARY, 27, 8, 40)), new Customer(9, "Peter", LocalDateTime.of(2019, Month.FEBRUARY, 1, 10, 11)), new Customer(2, "Bob", LocalDateTime.of(2019, Month.FEBRUARY, 1, 10, 11)), new Customer(5, "Jane", LocalDateTime.of(2019, Month.FEBRUARY, 24, 12, 04)) ); Comparator<Customer> byOrderTime = (c1, c2) -> { if (c1.getOrderTime().isBefore(c2.getOrderTime())) return -1; else return 1; }; List<Customer> newCustomers = customers.stream().sorted(byOrderTime.reversed()) .collect(Collectors.toList()); for(int i=0; i<newCustomers.size(); i++) { System.out.println(newCustomers.get(i)); } } } |
-> Output:
id = 3, name = Joe, birthday = 2019-02-27T08:40 id = 1, name = Jack, birthday = 2019-02-27T08:30 id = 5, name = Jane, birthday = 2019-02-24T12:04 id = 9, name = Peter, birthday = 2019-02-01T10:11 id = 2, name = Bob, birthday = 2019-02-01T10:11 id = 7, name = Mary, birthday = 2019-01-27T09:21 |
Conclusion
In this post, You learned how to sort with Java Object List by date proprety(java.util.Date
, LocalDate
, LocalDateTime
):
– Sorting Java Object List by Date proprety in Ascending & Descending order.
– Use Java Comparator & Java 8 with Lamda Expression syntax to implement examples.
– Implementing with collection sort API Collections.sort()
& new stream sort API: Collection.stream().sorted()
Hope it helpful for you! Thank you. See you next time.