You are here
Home > java >

How to Sort List by Date in Java 8 ?

How to Sort List by Date in Java 8 ?Sorting a List by Date sometimes becomes a bit tricky. One of the tricky part is how to handle date format and then perform the sorting. In this article ‘How to Sort List by Date in Java 8 ?’, we will discuss sorting of three types of Dates. These are java.util.Date,  java.time.LocalDate and java.time.LocalDateTime. Further, in order to sort the list, we will use three approaches. Using these approaches, we will utilize the new concepts introduced in Java 8. Moreover, these concepts are Lambda Expressions, Method References and Stream API. Let’s discuss about our topic ‘How to Sort List by Date in Java 8 ?’.

What type of dates are covered in this Article?

1) java.util.Date
2) java.time.LocalDate
3) java.time.LocalDateTime

What type of approaches are covered in this Article?

1) java 8 using Lambda Expression
2) java 8 using Method Reference
3) java 8 using Stream API
4) sort a List of Date/LocalDate/LocalDateTime in descending order in Java 8 using all above approaches

Sort List by Date in Java 8 with Lambda Expression

In order to implement sorting a List by Date, Let’s first create a POJO which will have a mandatory Date field. We will consider an entity as ‘Invoice’ to illustrate these examples. Further, we will declare 4 fields, including the java.util.Date field and other stuff as below.

import java.util.Date;

public class Invoice {

      private Integer id;
      private Double amount;
      private String number;
      private Date createdOn;

      public Invoice(Integer id, Double amount, String number, Date createdOn) {
              super();
              this.id = id;
              this.amount = amount;
              this.number = number;
              this.createdOn = createdOn;
      }

      public Integer getId() {
              return id;
      }
      public void setId(Integer id) {
             this.id = id;
      }
      public Double getAmount() {
             return amount;
      }
      public void setAmount(Double amount) {
             this.amount = amount;
      }
      public String getNumber() {
             return number;
      }
      public void setNumber(String number) {
             this.number = number;
      }
      public Date getCreatedOn() {
             return createdOn;
      }
      public void setCreatedOn(Date createdOn) {
            this.createdOn = createdOn;
      }

      @Override
      public String toString() {

             return String.format("id = %d, amount = %f, number = %s, createdOn = %s", this.id, this.amount, this.number, this.createdOn.toString());
      }

}

Next, we will have one more class where we will create some dummy records, apply sorting logics and then print the values. Let’s say it InvoiceService.java as below.

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class InvoiceService {

       private List<Invoice> getInvoiceList() throws ParseException {

       List<Invoice> invoices = Arrays.asList(
                            new Invoice(101, 496.67, "SQ078OPQ", new SimpleDateFormat("dd-MM-yyyy").parse("24-04-2020")),
                            new Invoice(102, 229.75, "QJ098OJH", new SimpleDateFormat("dd-MM-yyyy").parse("24-09-2020")),
                            new Invoice(103, 494.28, "RT048OQT", new SimpleDateFormat("dd-MM-yyyy").parse("21-04-2021")),
                            new Invoice(103, 195.56, "SR048OPR", new SimpleDateFormat("dd-MM-yyyy").parse("22-04-2021")),
                            new Invoice(103, 285.50, "JT048OTK", new SimpleDateFormat("dd-MM-yyyy").parse("04-12-2019"))
      );
      return invoices;
}

      public static void main(String[] args) throws ParseException {

               InvoiceService service = new InvoiceService();
               List<Invoice> list = service.getInvoiceList();
                
                Comparator<Invoice> comparator = (c1, c2) -> { 
                        return Long.valueOf(c1.getCreatedOn().getTime()).compareTo(c2.getCreatedOn().getTime()); 
                };

               Collections.sort(list, comparator);             
        list.forEach(System.out::println);    // System.out.println("Sorted List : " +list);             
       }
}

The important code of logic is as below. Rest of the codes are just for running the program successfully. Hence, our primary focus should be on this. For example, below code is the important part of our implementation. Further, if you face any difficulty to understand this code, kindly visit our article on Lambda Expression.

InvoiceService service = new InvoiceService();
List<Invoice> list = service.getInvoiceList();
Comparator<Invoice> comparator = (c1, c2) -> {
        return Long.valueOf(c1.getCreatedOn().getTime()).compareTo(c2.getCreatedOn().getTime());
};
Collections.sort(list, comparator);
list.forEach(System.out::println);

Output

id = 105, amount = 285.500000, number = JT048OTK, createdOn = Wed Dec 04 00:00:00 IST 2019
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = Fri Apr 24 00:00:00 IST 2020
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = Thu Sep 24 00:00:00 IST 2020
id = 103, amount = 494.280000, number = RT048OQT, createdOn = Wed Apr 21 00:00:00 IST 2021
id = 104, amount = 195.560000, number = SR048OPR, createdOn = Thu Apr 22 00:00:00 IST 2021

Sort List by Date in descending order

In order to get list in descending order we have two solutions.

1) Use reverse() method of Collections class
2) Modify Comparator for descending comparing order

Solution #1 : Use reverse() method of Collections class

Collections.reverse(list);
list.forEach(System.out::println);

Solution #2 : Modify Comparator for descending comparing order

List<Invoice> list = service.getInvoiceList();
Comparator<Invoice> reverseComparator = (c1, c2) -> { 
        return c2.getCreatedOn().compareTo(c1.getCreatedOn()); 
};
Collections.sort(list, reverseComparator);
list.forEach(System.out::println);

Output

id = 104, amount = 195.560000, number = SR048OPR, createdOn = Thu Apr 22 00:00:00 IST 2021
id = 103, amount = 494.280000, number = RT048OQT, createdOn = Wed Apr 21 00:00:00 IST 2021
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = Thu Sep 24 00:00:00 IST 2020
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = Fri Apr 24 00:00:00 IST 2020
id = 105, amount = 285.500000, number = JT048OTK, createdOn = Wed Dec 04 00:00:00 IST 2019

Sort List by Date in Java 8 with Method Reference

We can even use method reference to get sorted list. Needless to say, method references further minimizes the lines of code as shown below. Here, the Comparator.comparing() method accepts a method reference which evaluates the comparison logic. Hence, we will pass Invoice::getCreatedOn to sort it by the createdOn field. If you want to get more on comparing() method of Comparator, kindly visit Oracle Documentaion. Moreover, if you want to have deeper understanding on it, kindly visit our article on Method References.

List<Invoice> list = service.getInvoiceList();
list.sort(Comparator.comparing(Invoice::getCreatedOn));

list.forEach(System.out::println);

Output

id = 105, amount = 285.500000, number = JT048OTK, createdOn = Wed Dec 04 00:00:00 IST 2019
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = Fri Apr 24 00:00:00 IST 2020
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = Thu Sep 24 00:00:00 IST 2020
id = 103, amount = 494.280000, number = RT048OQT, createdOn = Wed Apr 21 00:00:00 IST 2021
id = 104, amount = 195.560000, number = SR048OPR, createdOn = Thu Apr 22 00:00:00 IST 2021

Sort List by Date in descending order

Let’s look at the code below. How simple is that code to sort a list in descending order !

List<Invoice> list = service.getInvoiceList();
list.sort(Comparator.comparing(Invoice::getCreatedOn).reversed());

list.forEach(System.out::println);

Output

id = 104, amount = 195.560000, number = SR048OPR, createdOn = Thu Apr 22 00:00:00 IST 2021
id = 103, amount = 494.280000, number = RT048OQT, createdOn = Wed Apr 21 00:00:00 IST 2021
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = Thu Sep 24 00:00:00 IST 2020
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = Fri Apr 24 00:00:00 IST 2020
id = 105, amount = 285.500000, number = JT048OTK, createdOn = Wed Dec 04 00:00:00 IST 2019

Sort List by Date in Java 8 with Stream API

Here we have another wat to sort a list. It’s just by using Stream API introduced in Java 8. Suppose we don’t want to modify the original list, but return the list as sorted. In this scenario, we can use the sorted() method from the Stream interface. For example, below code demonstrates the complete logic.

List<Invoice> sortedList = service.getInvoiceList().stream()
                  .sorted(Comparator.comparing(Invoice::getCreatedOn))
                  .collect(Collectors.toList());

sortedList.forEach(System.out::println);

Output

id = 105, amount = 285.500000, number = JT048OTK, createdOn = Wed Dec 04 00:00:00 IST 2019
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = Fri Apr 24 00:00:00 IST 2020 
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = Thu Sep 24 00:00:00 IST 2020
id = 103, amount = 494.280000, number = RT048OQT, createdOn = Wed Apr 21 00:00:00 IST 2021
id = 104, amount = 195.560000, number = SR048OPR, createdOn = Thu Apr 22 00:00:00 IST 2021

Sort List by Date in descending order

Let’s look at the code below. Again how simple is that code to sort a list in descending order !

List<Invoice> sortedList = service.getInvoiceList().stream()
                  .sorted(Comparator.comparing(Invoice::getCreatedOn).reversed())
                  .collect(Collectors.toList());

sortedList.forEach(System.out::println);

Output

id = 104, amount = 195.560000, number = SR048OPR, createdOn = Thu Apr 22 00:00:00 IST 2021
id = 103, amount = 494.280000, number = RT048OQT, createdOn = Wed Apr 21 00:00:00 IST 2021
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = Thu Sep 24 00:00:00 IST 2020
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = Fri Apr 24 00:00:00 IST 2020 
id = 105, amount = 285.500000, number = JT048OTK, createdOn = Wed Dec 04 00:00:00 IST 2019

Sort List by LocalDate in Java 8 with Lambda Expression

In this example we will sort our list by LocalDate which is programmatically different than java.util.Date. This LocalDate comes under java.time package. In order to implement sorting a List by LocalDate, Let’s first create a POJO which will have a LocalDate field mandatorily. We will consider an entity as ‘Invoice’ to illustrate these examples. Further, we will declare 4 fields including the java.time.LocalDate field and other stuff as below.

import java.time.LocalDate;

public class Invoice {

      private Integer id;
      private Double amount;
      private String number;
      private LocalDate createdOn;

      public Invoice(Integer id, Double amount, String number, LocalDate createdOn) {
              super();
              this.id = id;
              this.amount = amount;
              this.number = number;
              this.createdOn = createdOn;
      }

      public Integer getId() {
              return id;
      }
      public void setId(Integer id) {
             this.id = id;
      }
      public Double getAmount() {
             return amount;
      }
      public void setAmount(Double amount) {
             this.amount = amount;
      }
      public String getNumber() {
             return number;
      }
      public void setNumber(String number) {
             this.number = number;
      }
      public LocalDate getCreatedOn() {
             return createdOn;
      }
      public void setCreatedOn(LocalDate createdOn) {
            this.createdOn = createdOn;
      }

      @Override
      public String toString() {

             return String.format("id = %d, amount = %f, number = %s, createdOn = %s", this.id, this.amount, this.number, this.createdOn.toString());
      }

}

Next, we will have one more class where we will create some dummy records, apply sorting logics and then print the values. Let’s say it InvoiceService.java as below.

import java.text.ParseException;
import java.time.LocalDate;
import java.time.Month;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class InvoiceService {

       private List<Invoice> getInvoiceList() throws ParseException {

       List<Invoice> invoices = Arrays.asList(
                            new Invoice(101, 496.67, "SQ078OPQ", LocalDate.of(2020, Month.APRIL, 24)),
                            new Invoice(102, 229.75, "QJ098OJH", LocalDate.of(2020, Month.SEPTEMBER, 24)),
                            new Invoice(103, 494.28, "RT048OQT", LocalDate.of(2021, Month.APRIL, 21)),
                            new Invoice(103, 195.56, "SR048OPR", LocalDate.of(2021, Month.APRIL, 22)),
                            new Invoice(103, 285.50, "JT048OTK", LocalDate.of(2019, Month.DECEMBER, 04))
      );
      return invoices;
}

      public static void main(String[] args) throws ParseException {

               InvoiceService service = new InvoiceService();
               List<Invoice> list = service.getInvoiceList();
                
                Comparator<Invoice> comparator = (c1, c2) -> { 
                        return c1.getCreatedOn().compareTo(c2.getCreatedOn()); 
                };

               Collections.sort(list, comparator);             
        list.forEach(System.out::println);    // System.out.println("Sorted List : " +list);             
       }
}

The important code of logic is as below. Rest of the codes are just for running the program successfully. Hence, our primary focus should be on this. For example, below code is the important part of our implementation. Further, if you face any difficulty to understand this code, kindly visit our article on Lambda Expression.

InvoiceService service = new InvoiceService();
List<Invoice> list = service.getInvoiceList();
Comparator<Invoice> comparator = (c1, c2) -> {
        return c1.getCreatedOn().compareTo(c2.getCreatedOn());
};
Collections.sort(list, comparator);
list.forEach(System.out::println);

Output

id = 105, amount = 285.500000, number = JT048OTK, createdOn = 2019-12-04
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = 2020-04-24
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = 2020-09-24
id = 103, amount = 494.280000, number = RT048OQT, createdOn = 2021-04-21
id = 104, amount = 195.560000, number = SR048OPR, createdOn = 2021-04-22

Sort List by LocalDate in descending order

In order to get list in descending order we have two solutions.

1) Use reverse() method of Collections class
2) Modify Comparator for descending comparing order

Solution #1 : Use reverse() method of Collections class

Collections.reverse(list);
list.forEach(System.out::println);

Solution #2 : Modify Comparator for descending comparing order

List<Invoice> list = service.getInvoiceList();
Comparator<Invoice> reverseComparator = (c1, c2) -> { 
        return c2.getCreatedOn().compareTo(c1.getCreatedOn()); 
};
Collections.sort(list, reverseComparator);
list.forEach(System.out::println);

Output

id = 104, amount = 195.560000, number = SR048OPR, createdOn = 2021-04-22
id = 103, amount = 494.280000, number = RT048OQT, createdOn = 2021-04-21
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = 2020-09-24
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = 2020-04-24
id = 105, amount = 285.500000, number = JT048OTK, createdOn = 2019-12-04

Sort List by LocalDate in Java 8 with Method Reference

We can even use method reference to get sorted list. Needless to say, method references further minimizes the lines of code as shown below. Here, the Comparator.comparing() method accepts a method reference which evaluates the comparison logic.  Hence, we will pass Invoice::getCreatedOn to sort it by the createdOn field. If you want to get more on comparing() method of Comparator, kindly visit Oracle Documentaion. Moreover, if you want to have deeper understanding on it, kindly visit our article on Method References.

List<Invoice> list = service.getInvoiceList();
list.sort(Comparator.comparing(Invoice::getCreatedOn));

list.forEach(System.out::println);

Output

id = 105, amount = 285.500000, number = JT048OTK, createdOn = 2019-12-04
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = 2020-04-24
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = 2020-09-24
id = 103, amount = 494.280000, number = RT048OQT, createdOn = 2021-04-21
id = 104, amount = 195.560000, number = SR048OPR, createdOn = 2021-04-22

Sort List by LocalDate in descending order

Let’s look at the code below. How simple is that code to sort a list in descending order !

List<Invoice> list = service.getInvoiceList();
list.sort(Comparator.comparing(Invoice::getCreatedOn).reversed());

list.forEach(System.out::println);

Output

id = 104, amount = 195.560000, number = SR048OPR, createdOn = 2021-04-22
id = 103, amount = 494.280000, number = RT048OQT, createdOn = 2021-04-21
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = 2020-09-24
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = 2020-04-24
id = 105, amount = 285.500000, number = JT048OTK, createdOn = 2019-12-04

Sort List by LocalDate in Java 8 with Stream API

Here we have another wat to sort a list. It’s just by using Stream API introduced in Java 8. Suppose we don’t want to modify the original list, but return the list as sorted. In this scenario, we can use the sorted() method from the Stream interface. For example, below code demonstrates the complete logic.

List<Invoice> sortedList = service.getInvoiceList().stream()
                  .sorted(Comparator.comparing(Invoice::getCreatedOn))
                  .collect(Collectors.toList());

sortedList.forEach(System.out::println);

Output

id = 105, amount = 285.500000, number = JT048OTK, createdOn = 2019-12-04
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = 2020-04-24
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = 2020-09-24
id = 103, amount = 494.280000, number = RT048OQT, createdOn = 2021-04-21
id = 104, amount = 195.560000, number = SR048OPR, createdOn = 2021-04-22

Sort List by LocalDate in descending order

Let’s look at the code below. Again how simple is that code to sort a list in descending order !

List<Invoice> sortedList = service.getInvoiceList().stream()
                  .sorted(Comparator.comparing(Invoice::getCreatedOn).reversed())
                  .collect(Collectors.toList());

sortedList.forEach(System.out::println);

Output

id = 104, amount = 195.560000, number = SR048OPR, createdOn = 2021-04-22
id = 103, amount = 494.280000, number = RT048OQT, createdOn = 2021-04-21
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = 2020-09-24
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = 2020-04-24
id = 105, amount = 285.500000, number = JT048OTK, createdOn = 2019-12-04

Sort List by LocalDateTime in Java 8

Sometimes we need to work on LocalDateTime which is used to display date including timestamps. This LocalDateTime also comes under java.time package. In order to implement sorting a List by LocalDateTime, Let’s first create a POJO which will have a LocalDateTime field mandatorily. We will consider an entity as ‘Invoice’ to illustrate these examples. Further, we will declare 4 fields including the java.time.LocalDateTime field and other stuff as below.

import java.time.LocalDateTime;

public class Invoice {

      private Integer id;
      private Double amount;
      private String number;
      private LocalDateTime createdOn;

      public Invoice(Integer id, Double amount, String number, LocalDateTime createdOn) {
              super();
              this.id = id;
              this.amount = amount;
              this.number = number;
              this.createdOn = createdOn;
      }

      public Integer getId() {
              return id;
      }
      public void setId(Integer id) {
             this.id = id;
      }
      public Double getAmount() {
             return amount;
      }
      public void setAmount(Double amount) {
             this.amount = amount;
      }
      public String getNumber() {
             return number;
      }
      public void setNumber(String number) {
             this.number = number;
      }
      public LocalDateTime getCreatedOn() {
             return createdOn;
      }
      public void setCreatedOn(LocalDateTime createdOn) {
            this.createdOn = createdOn;
      }

      @Override
      public String toString() {

             return String.format("id = %d, amount = %f, number = %s, createdOn = %s", this.id, this.amount, this.number, this.createdOn.toString());
      }

}

Next, we will have one more class where we will create some dummy records, apply sorting logics and then print the values. Let’s say it InvoiceService.java as below.

import java.text.ParseException;
import java.time.LocalDate;
import java.time.Month;
import java.util.Arrays;
import java.util.Collections;
import java.util.List;

public class InvoiceService {

       private List<Invoice> getInvoiceList() throws ParseException {

       List<Invoice> invoices = Arrays.asList(
                            new Invoice(101, 496.67, "SQ078OPQ", LocalDateTime.of(2020, Month.APRIL, 24, 9, 44, 15)),
                            new Invoice(102, 229.75, "QJ098OJH", LocalDateTime.of(2020, Month.SEPTEMBER, 24, 11, 52, 8)),
                            new Invoice(103, 494.28, "RT048OQT", LocalDateTime.of(2021, Month.APRIL, 21, 21, 16, 24)),
                            new Invoice(103, 195.56, "SR048OPR", LocalDateTime.of(2021, Month.APRIL, 22, 7, 30, 24)),
                            new Invoice(103, 285.50, "JT048OTK", LocalDateTime.of(2019, Month.DECEMBER, 04, 10, 15, 40))
      );
      return invoices;
}

      public static void main(String[] args) throws ParseException {

               InvoiceService service = new InvoiceService();
               List<Invoice> list = service.getInvoiceList();
                
                Comparator<Invoice> comparator = (c1, c2) -> { 
                        return c1.getCreatedOn().compareTo(c2.getCreatedOn()); 
                };

               Collections.sort(list, comparator);             
        list.forEach(System.out::println);    // System.out.println("Sorted List : " +list);             
       }
}

The important code of logic is as below. Rest of the codes are just for running the program successfully. Hence, our primary focus should be on this. For example, below code is the important part of our implementation. Further, if you face any difficulty to understand this code, kindly visit our article on Lambda Expression.

InvoiceService service = new InvoiceService();
List<Invoice> list = service.getInvoiceList();
Comparator<Invoice> comparator = (c1, c2) -> {
        return c1.getCreatedOn().compareTo(c2.getCreatedOn());
};
Collections.sort(list, comparator);
list.forEach(System.out::println);

Output

id = 105, amount = 285.500000, number = JT048OTK, createdOn = 2019-12-04T10:15:40
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = 2020-04-24T09:44:15
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = 2020-09-24T11:52:08
id = 103, amount = 494.280000, number = RT048OQT, createdOn = 2021-04-21T21:16:24
id = 104, amount = 195.560000, number = SR048OPR, createdOn = 2021-04-22T07:30:24

Sort List by LocalDateTime in descending order

In order to get list in descending order we have two solutions.

1) Use reverse() method of Collections class
2) Modify Comparator for descending comparing order

Solution #1 : Use reverse() method of Collections class

Collections.reverse(list);
list.forEach(System.out::println);

Solution #2 : Modify Comparator for descending comparing order

List<Invoice> list = service.getInvoiceList();
Comparator<Invoice> reverseComparator = (c1, c2) -> { 
        return c2.getCreatedOn().compareTo(c1.getCreatedOn()); 
};
Collections.sort(list, reverseComparator);
list.forEach(System.out::println);

Output

id = 104, amount = 195.560000, number = SR048OPR, createdOn = 2021-04-22T07:30:24
id = 103, amount = 494.280000, number = RT048OQT, createdOn = 2021-04-21T21:16:24
id = 102, amount = 229.750000, number = QJ098OJH, createdOn = 2020-09-24T11:52:08
id = 101, amount = 496.670000, number = SQ078OPQ, createdOn = 2020-04-24T09:44:15
id = 105, amount = 285.500000, number = JT048OTK, createdOn = 2019-12-04T10:15:40

Similarly, we can implement other approaches to sort a list of LocalDatetime. 

Summary

As we have discussed enough examples in this article to sort a list of Dates. Moreover, we have discussed multiple formats of Dates to sort. After going through this article on ‘How to Sort List by Date in Java 8 ?’, you should be able to work in Sorting of any type of Date confidently. Since requirement of Topic is to use Java 8, we have utilized the same in enough amount. I hope, you will also apply these concepts in your project. If we find any other approaches to do it better, we will also update the article. Please provide your comments in the comment box on this topic ‘How to Sort List by Date in Java 8 ?’.

 

 

close

Leave a Reply

Top