Java 8 – How to Sort List by LocalDateTime in 4 ways ?

In this article, we will discuss and learn how to sort List by java.time.LocalDatetime in ascending as well as descending order in different ways

Sort List by LocalDateTime in 4 ways:

  1. Using java.util.Comparator
  2. Using Lambda expression
  3. Using Method References
  4. Using Stream API

We have Product class with 4 member variables, its setters & getters, 4-arg parameterized constructor and overriding toString() method for pretty print. We will sort List of Products on the basis of java.time.LocalDateTime in ascending and descending order in 4 different ways as mentioned above.

Product.java

package in.bench.resources.localdatetime.sorting;

import java.time.LocalDateTime;

public class Product {

	// member variables
	private int prodId;
	private String prodName;
	private LocalDateTime prodCreatedDate;
	private double prodRate;


	// getters and setters


	// 4-arg parameterized constructor


	// override toString() method
	@Override
	public String toString() {
		return "Product [prodId=" + prodId 
				+ ", prodCreatedDate=" + prodCreatedDate
				+ ", prodRate=" + prodRate 
				+ ", prodName=" + prodName 
				+ "]";
	}
}

1. Sort List by LocalDateTime using java.util.Comparator :

  • There is a list of Products and we will be sorting product list by LocalDateTime in ascending and descending order using java.util.Comparator interface
  • For sorting,
    • We will create separate class implementing java.util.Comparator interface and overriding compare() method for ascending-order sorting
    • For descending-order sorting, we will reverse the Comparator using reversed() method
  • Finally, we will print product list to console in ascending and descending order

ProductSortingComparator.java

package in.bench.resources.localdatetime.sorting;

import java.util.Comparator;

public class ProductSortingComparator implements Comparator<Product> {

	@Override
	public int compare(Product prod1, Product prod2) {
		return prod1.getProdCreatedDate().compareTo(prod2.getProdCreatedDate());
	}
}

ProductLocalDateTimeSortingUsingComparator.java

package in.bench.resources.localdatetime.sorting;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class ProductLocalDateTimeSortingUsingComparator {

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

		// 1. products
		Product product1 = new Product(1, "Cooker", 
				LocalDateTime.of(2022, Month.MAY, 31, 12, 35, 59), 13750.0);
		Product product2 = new Product(2, "Sofa-Bed", 
				LocalDateTime.of(2022, Month.MAY, 31, 11, 49, 53), 11750.0);
		Product product3 = new Product(3, "Fridge", 
				LocalDateTime.of(2022, Month.JUNE, 18, 5, 30, 49), 12750.0);
		Product product4 = new Product(4, "Cupboard", 
				LocalDateTime.of(2022, Month.JUNE, 18, 4, 45, 37), 11525.0);
		Product product5 = new Product(5, "Utensils", 
				LocalDateTime.of(2022, Month.JANUARY, 10, 12, 45, 01), 17050.0);


		// 1.1 List of Products
		List<Product> products = new ArrayList<Product>();
		products.add(product1);
		products.add(product2);
		products.add(product3);
		products.add(product4);
		products.add(product5);


		// 1.2 print to console
		System.out.println("Before sorting :- \n");
		for(Product prod : products) {
			System.out.println(prod);
		}


		// 2. Ascending-order sorting
		Collections.sort(products, new ProductSortingComparator());


		// 2.1 print to console - ascending order
		System.out.println("\n\nAscending-order sorting on the basis of LocalDateTime :- \n");
		for(Product prod : products) {
			System.out.println(prod);
		}


		// 3. Descending-order sorting
		Collections.sort(products, (new ProductSortingComparator()).reversed());


		// 3.1 print to console - descending order
		System.out.println("\n\nDescending-order sorting on the basis of LocalDateTime :- \n");
		for(Product prod : products) {
			System.out.println(prod);
		}
	}
}

Output:

Before sorting :- 

Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]


Ascending-order sorting on the basis of LocalDateTime :- 

Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]


Descending-order sorting on the basis of LocalDateTime :- 

Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]

2. Sort List by LocalDateTime using Lambda Expression :

  • There is a list of Products and we will be sorting product list by LocalDateTime in ascending and descending order using Lambda Expression
  • For sorting, we will write/code lambda expression to sort list of product on the basis of product created date which will return Comparator
    • For ascending-order sorting, we will pass actual list and Comparator to Collections.sort() method
    • For descending-order sorting, we will reverse the Comparator using reversed() method of Comparator and pass actual list and reversed Comparator to Collections.sort() method
  • Finally, we will print product list to console in ascending and descending order

ProductLocalDateTimeSortingUsingLambdaExpression.java

package in.bench.resources.localdatetime.sorting;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.Collections;
import java.util.Comparator;
import java.util.List;

public class ProductLocalDateTimeSortingUsingLambdaExpression {

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

		// 1. products
		Product product1 = new Product(1, "Cooker", 
				LocalDateTime.of(2022, Month.MAY, 31, 12, 35, 59), 13750.0);
		Product product2 = new Product(2, "Sofa-Bed", 
				LocalDateTime.of(2022, Month.MAY, 31, 11, 49, 53), 11750.0);
		Product product3 = new Product(3, "Fridge", 
				LocalDateTime.of(2022, Month.JUNE, 18, 5, 30, 49), 12750.0);
		Product product4 = new Product(4, "Cupboard", 
				LocalDateTime.of(2022, Month.JUNE, 18, 4, 45, 37), 11525.0);
		Product product5 = new Product(5, "Utensils", 
				LocalDateTime.of(2022, Month.JANUARY, 10, 12, 45, 01), 17050.0);


		// 1.1 List
		List<Product> products = new ArrayList<Product>();
		products.add(product1);
		products.add(product2);
		products.add(product3);
		products.add(product4);
		products.add(product5);


		// 1.2 print to console
		System.out.println("Before sorting :- \n");
		products.forEach(prod -> System.out.println(prod));


		// 2. get Comparator using Lambda expression
		Comparator<Product> comparatorAsc = (prod1, prod2) -> prod1.getProdCreatedDate()
				.compareTo(prod2.getProdCreatedDate());


		// 2.1 pass above Comparator and sort in ascending order
		Collections.sort(products, comparatorAsc);


		// 2.2 print to console
		System.out.println("\n\nAscending-order sorting on the basis of LocalDateTime :- \n");
		products.forEach(prod -> System.out.println(prod));


		// 3. get Comparator using Lambda expression
		Comparator<Product> comparatorDesc = (prod1, prod2) -> prod2.getProdCreatedDate()
				.compareTo(prod1.getProdCreatedDate());


		// 3.1 pass above Comparator and sort in descending order
		Collections.sort(products, comparatorDesc);


		// 3.2 print to console - descending order
		System.out.println("\n\nDescending-order sorting on the basis of LocalDateTime :- \n");
		products.forEach(prod -> System.out.println(prod));
	}
}

Output:

Before sorting :- 

Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]


Ascending-order sorting on the basis of LocalDateTime :- 

Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]


Descending-order sorting on the basis of LocalDateTime :- 

Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]

3. Sort List by LocalDateTime using Method References :

  • There is a list of Products and we will be sorting product list by LocalDateTime in ascending and descending order using Method References
  • For sorting, create a Comparator by passing Method References to Comparator.comparing() method
    • For ascending-order sorting, pass above created Comparator to List.sort() method as argument
    • For descending-order sorting, we will reverse the Comparator using reversed() method of Comparator and pass reversed Comparator to List.sort() method as argument
  • Finally, we will print product list to console in ascending and descending order

ProductLocalDateTimeSortingUsingMethodReferences.java

package in.bench.resources.localdatetime.sorting;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class ProductLocalDateTimeSortingUsingMethodReferences {

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

		// 1. products
		Product product1 = new Product(1, "Cooker", 
				LocalDateTime.of(2022, Month.MAY, 31, 12, 35, 59), 13750.0);
		Product product2 = new Product(2, "Sofa-Bed", 
				LocalDateTime.of(2022, Month.MAY, 31, 11, 49, 53), 11750.0);
		Product product3 = new Product(3, "Fridge", 
				LocalDateTime.of(2022, Month.JUNE, 18, 5, 30, 49), 12750.0);
		Product product4 = new Product(4, "Cupboard", 
				LocalDateTime.of(2022, Month.JUNE, 18, 4, 45, 37), 11525.0);
		Product product5 = new Product(5, "Utensils", 
				LocalDateTime.of(2022, Month.JANUARY, 10, 12, 45, 01), 17050.0);


		// 1.1 List
		List<Product> products = new ArrayList<Product>();
		products.add(product1);
		products.add(product2);
		products.add(product3);
		products.add(product4);
		products.add(product5);


		// 1.2 print to console
		System.out.println("Before sorting :- \n");
		products.forEach(System.out::println);


		// 2. ascending-order sorting using Method References
		products.sort(Comparator.comparing(Product::getProdCreatedDate));


		// 2.1 print to console
		System.out.println("\n\nAscending-order sorting on the basis of LocalDateTime :- \n");
		products.forEach(System.out::println);


		// 3. descending-order sorting using Method References
		products.sort(Comparator.comparing(Product::getProdCreatedDate).reversed());


		// 3.1 print to console - descending order
		System.out.println("\n\nDescending-order sorting on the basis of LocalDateTime :- \n");
		products.forEach(System.out::println);
	}
}

Output:

Before sorting :- 

Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]


Ascending-order sorting on the basis of LocalDateTime :- 

Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]


Descending-order sorting on the basis of LocalDateTime :- 

Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]

4. Sort List by LocalDateTime using Stream API :

ProductLocalDateTimeSortingUsingStreamAPI.java

package in.bench.resources.localdatetime.sorting;

import java.text.ParseException;
import java.time.LocalDateTime;
import java.time.Month;
import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

public class ProductLocalDateTimeSortingUsingStreamAPI {

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

		// 1. products
		Product product1 = new Product(1, "Cooker", 
				LocalDateTime.of(2022, Month.MAY, 31, 12, 35, 59), 13750.0);
		Product product2 = new Product(2, "Sofa-Bed", 
				LocalDateTime.of(2022, Month.MAY, 31, 11, 49, 53), 11750.0);
		Product product3 = new Product(3, "Fridge", 
				LocalDateTime.of(2022, Month.JUNE, 18, 5, 30, 49), 12750.0);
		Product product4 = new Product(4, "Cupboard", 
				LocalDateTime.of(2022, Month.JUNE, 18, 4, 45, 37), 11525.0);
		Product product5 = new Product(5, "Utensils", 
				LocalDateTime.of(2022, Month.JANUARY, 10, 12, 45, 01), 17050.0);


		// 1.1 List
		List<Product> products = new ArrayList<Product>();
		products.add(product1);
		products.add(product2);
		products.add(product3);
		products.add(product4);
		products.add(product5);


		// 1.2 print to console
		System.out.println("Before sorting :- \n");
		products.stream().forEach(prod -> System.out.println(prod));


		// 2. ascending-order sorting
		List<Product> sortedProductListAsc = products
				.stream()
				.sorted(Comparator.comparing(Product::getProdCreatedDate))
				.collect(Collectors.toList());


		// 2.1 print to console
		System.out.println("\n\nAscending-order sorting on the basis of LocalDateTime :- \n");
		sortedProductListAsc.stream().forEach(prod -> System.out.println(prod));


		// 3. descending-order sorting
		List<Product> sortedProductListDesc = products
				.stream()
				.sorted(Comparator.comparing(Product::getProdCreatedDate).reversed())
				.collect(Collectors.toList());


		// 3.1 print to console - descending order
		System.out.println("\n\nDescending-order sorting on the basis of LocalDateTime :- \n");
		sortedProductListDesc.stream().forEach(prod -> System.out.println(prod));
	}
}

Output:

Before sorting :- 

Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]


Ascending-order sorting on the basis of LocalDateTime :- 

Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]


Descending-order sorting on the basis of LocalDateTime :- 

Product [prodId=3, prodCreatedDate=2022-06-18T05:30:49, prodRate=12750.0, prodName=Fridge]
Product [prodId=4, prodCreatedDate=2022-06-18T04:45:37, prodRate=11525.0, prodName=Cupboard]
Product [prodId=1, prodCreatedDate=2022-05-31T12:35:59, prodRate=13750.0, prodName=Cooker]
Product [prodId=2, prodCreatedDate=2022-05-31T11:49:53, prodRate=11750.0, prodName=Sofa-Bed]
Product [prodId=5, prodCreatedDate=2022-01-10T12:45:01, prodRate=17050.0, prodName=Utensils]

Related Articles:

References:

Happy Coding !!
Happy Learning !!

Java 8 - LocalDate with method details and examples
Java 8 - How to Sort List by LocalDate in 4 ways ?