How to Sort a List of Date in Java

Tags: DateUtils Java Date

In this Java tutorial, we learn how to implement a utility Java method to sort a List of Date objects in Java programming language.

How to sort a List of Date objects in Java

At this first step, create a new Java class named DateUtils, and a new static method named sortDates(List dates), this method to sort a given List of Date objects using Java Stream API and return a sorted List of Date objects as the following Java code.

DateUtils.java

import java.util.Comparator;
import java.util.Date;
import java.util.List;
import java.util.stream.Collectors;

public class DateUtils {

    /**
     * This method to return a list of sorted Date objects
     * @param dates input List of dates
     * @return sorted List of dates
     */
    public static List<Date> sortDates(List<Date> dates) {
        return dates.stream()
                .sorted(Comparator.comparing(Date::getTime))
                .collect(Collectors.toList());
    }
}

In the following example Java code, we learn how to use the above DateUtils.sortDates(List dates) method in Java program.

DateUtilsSortDatesExample.java

import java.text.ParseException;
import java.text.SimpleDateFormat;
import java.util.ArrayList;
import java.util.Date;
import java.util.List;

public class DateUtilsSortDatesExample {
    public static void main(String... args) throws ParseException {
        SimpleDateFormat simpleDateFormat = new SimpleDateFormat("yyyy/MM/dd");
        List<Date> dates = new ArrayList<>();

        dates.add(simpleDateFormat.parse("2022/08/01"));
        dates.add(simpleDateFormat.parse("2022/07/11"));
        dates.add(simpleDateFormat.parse("2022/09/03"));
        dates.add(simpleDateFormat.parse("2022/02/07"));
        dates.add(simpleDateFormat.parse("2022/03/08"));

        // Sort a List of Date objects
        List<Date> sortedDates = DateUtils.sortDates(dates);

        System.out.println("Dates:");
        System.out.println(dates);
        System.out.println("Sorted Dates:");
        System.out.println(sortedDates);
    }
}
The output as below.
Dates:
[Mon Aug 01 00:00:00 ICT 2022, Mon Jul 11 00:00:00 ICT 2022, Sat Sep 03 00:00:00 ICT 2022, Mon Feb 07 00:00:00 ICT 2022, Tue Mar 08 00:00:00 ICT 2022]
Sorted Dates:
[Mon Feb 07 00:00:00 ICT 2022, Tue Mar 08 00:00:00 ICT 2022, Mon Jul 11 00:00:00 ICT 2022, Mon Aug 01 00:00:00 ICT 2022, Sat Sep 03 00:00:00 ICT 2022]

Happy Coding 😊

How to Use TemporalAdjusters in Java

Java Add Number of Days to Current Date

Java Add Number of Days to Current LocalDate

Java Add Number of Days to Current LocalDateTime

Java Add Number of Days to Current OffsetDateTime

Java Add Number of Days to Current ZonedDateTime