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
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:
- Using
java.util.Collections.sort(List list, Comparator super Customer> c)
: sorting the specified list according to the order providing by the specified comparator. - Using Java 8 Stream API to sort
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 Stream + Lamda Expression) by descending and ascending sorting order.
Overview 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 contractUsing Collections.sort() - Sorting Java Objects Examples by java.util.Date property
We create a Java Class Object that has abirthday
property withjava.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:
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
Top comments (0)