Javatpoint Logo
Javatpoint Logo

Sort Dates in Java

The sort() method that is a part of Comparator mechanism of Collection class that sorts the data in decreasing order.

If we want to achieve the aim in generic while considering the boundary condition where the objects to be sorted are user-defined, we can use Comparator interface. Both ways are discussed below, where the user-defined type is also used to generate the object.

There are several ways in Java for sorting things in an ArrayList by date. It can be accomplished either by using the Comparable<> interface or the Collections.sort() method; we can use any of the following ways.

  1. Comparator interface
  2. sort() method

1. Comparator interface

Java Programs to sort elements of ArrayList by Date using Comparator interface.

SortDate1.java

Output:

Dates sorted in Ascending Order
1998-02-20
1999-04-26
2019-06-24
2021-05-14

Let's see another example.

SortDate2.java

Output:

Dates sorted in Descending Order
2021-05-14
2019-06-24
1999-04-26
1998-02-20

2. sort() method

Java Programs to sort elements of ArrayList by Date using Collections.sort() method

SortDate3.java

Output:

Dates Object before sorting: 
2020-03-25
2019-01-27
2020-03-26
2020-02-26
Dates Object after sorting: 
2019-01-27
2020-02-26
2020-03-25
2020-03-26

SortDate4.java

Output:

---> Date & Time Object List Before Sort (MM/dd/yyyy '@'hh:mm a)
05/12/2012 @05:16 AM
03/23/2014 @11:26 AM
02/13/2011 @09:36 AM
11/12/2013 @05:16 AM
08/11/2017 @09:26 PM
09/05/2016 @07:36 PM
---> Date & Time Object List After Sort (MM/dd/yyyy '@'hh:mm a)
02/13/2011 @09:36 AM
05/12/2012 @05:16 AM
11/12/2013 @05:16 AM
03/23/2014 @11:26 AM
09/05/2016 @07:36 PM
08/11/2017 @09:26 PM
---> Date & Time List Before Sort (MM/dd/yyyy '@'hh:mm a)
01/21/2014 @03:13 PM
01/21/2011 @04:37 PM
01/21/2012 @10:41 AM
01/21/2013 @10:48 AM
01/22/2015 @06:16 AM
01/22/2013 @06:19 AM
01/21/2018 @05:19 PM
01/21/2013 @05:19 PM
---> Date & Time List After Sort (MM/dd/yyyy '@'hh:mm a)
01/21/2011 @04:37 PM
01/21/2012 @10:41 AM
01/21/2013 @10:48 AM
01/21/2013 @05:19 PM
01/22/2013 @06:19 AM
01/21/2014 @03:13 PM
01/22/2015 @06:16 AM
01/21/2018 @05:19 PM






Youtube For Videos Join Our Youtube Channel: Join Now

Feedback


Help Others, Please Share

facebook twitter pinterest

Learn Latest Tutorials


Preparation


Trending Technologies


B.Tech / MCA