Java 8 Lambda - Java Sort an Array of Objects in Ascending and Descending Order

📘 Premium Read: Access my best content on Medium member-only articles — deep dives into Java, Spring Boot, Microservices, backend architecture, interview preparation, career advice, and industry-standard best practices.

🎓 Top 15 Udemy Courses (80-90% Discount): My Udemy Courses - Ramesh Fadatare — All my Udemy courses are real-time and project oriented courses.

▶️ Subscribe to My YouTube Channel (176K+ subscribers): Java Guides on YouTube

▶️ For AI, ChatGPT, Web, Tech, and Generative AI, subscribe to another channel: Ramesh Fadatare on YouTube

Introduction

With the introduction of lambdas in Java 8, sorting arrays and collections has become more concise and readable. Lambdas allow you to pass a block of code (an implementation of a functional interface) as an argument to methods. In this tutorial, we will explore how to use lambdas to sort an array of objects in both ascending and descending order.

Table of Contents

  1. What is a Lambda Expression?
  2. Sorting with Lambdas
  3. Complete Example Program
  4. Conclusion

1. What is a Lambda Expression?

A lambda expression is a compact way of writing anonymous classes that implement a functional interface. It has a syntax that is more concise and readable. A lambda expression consists of three parts:

  1. Argument list: (parameters)
  2. Arrow token: ->
  3. Body: {statements}

Example:

(parameters) -> {statements} 

2. Sorting with Lambdas

Example Class:

Let's consider a Person class with attributes name and age.

class Person { private String name; private int age; public Person(String name, int age) { this.name = name; this.age = age; } public String getName() { return name; } public int getAge() { return age; } @Override public String toString() { return "Person{name='" + name + "', age=" + age + '}'; } } 

Sorting in Ascending Order

To sort an array of Person objects in ascending order by age using lambdas, you can pass a lambda expression to the Arrays.sort method.

Arrays.sort(people, (p1, p2) -> Integer.compare(p1.getAge(), p2.getAge())); 

Sorting in Descending Order

To sort an array of Person objects in descending order by age using lambdas, you can pass a lambda expression that reverses the comparison.

Arrays.sort(people, (p1, p2) -> Integer.compare(p2.getAge(), p1.getAge())); 

3. Complete Example Program

Here is a complete example program that demonstrates how to sort an array of Person objects in both ascending and descending order using lambdas.

Example Code:

import java.util.Arrays; public class SortArrayObjectsWithLambdas { public static void main(String[] args) { // Create an array of Person objects Person[] people = { new Person("Alice", 30), new Person("Bob", 25), new Person("Charlie", 35) }; // Print the array before sorting System.out.println("Before sorting:"); printArray(people); // Sort the array in ascending order by age Arrays.sort(people, (p1, p2) -> Integer.compare(p1.getAge(), p2.getAge())); System.out.println("After sorting by age in ascending order:"); printArray(people); // Sort the array in descending order by age Arrays.sort(people, (p1, p2) -> Integer.compare(p2.getAge(), p1.getAge())); System.out.println("After sorting by age in descending order:"); printArray(people); // Sort the array in ascending order by name Arrays.sort(people, (p1, p2) -> p1.getName().compareTo(p2.getName())); System.out.println("After sorting by name in ascending order:"); printArray(people); // Sort the array in descending order by name Arrays.sort(people, (p1, p2) -> p2.getName().compareTo(p1.getName())); System.out.println("After sorting by name in descending order:"); printArray(people); } // Method to print the array private static void printArray(Person[] array) { for (Person person : array) { System.out.println(person); } } } 

Output:

Before sorting: Person{name='Alice', age=30} Person{name='Bob', age=25} Person{name='Charlie', age=35} After sorting by age in ascending order: Person{name='Bob', age=25} Person{name='Alice', age=30} Person{name='Charlie', age=35} After sorting by age in descending order: Person{name='Charlie', age=35} Person{name='Alice', age=30} Person{name='Bob', age=25} After sorting by name in ascending order: Person{name='Alice', age=30} Person{name='Bob', age=25} Person{name='Charlie', age=35} After sorting by name in descending order: Person{name='Charlie', age=35} Person{name='Bob', age=25} Person{name='Alice', age=30} 

Explanation:

  1. Person Class:

    • The Person class has attributes name and age with corresponding getters.
    • The toString method is overridden to provide a readable string representation of Person objects.
  2. SortArrayObjectsWithLambdas Class:

    • The main method demonstrates how to use lambda expressions to sort an array of Person objects by their age and name in both ascending and descending order.
    • The Arrays.sort method is used with lambda expressions to define custom sorting orders.
    • The sorted array is printed after each sort operation.

4. Conclusion

Lambdas in Java 8 provide a concise and readable way to sort arrays and collections. By using lambda expressions, you can easily define custom sorting orders without the need for separate comparator classes. This tutorial has demonstrated how to use lambdas to sort an array of custom objects in both ascending and descending order by different attributes. Understanding and using lambdas effectively can greatly enhance your ability to write clean and efficient Java code.

Comments

Spring Boot 3 Paid Course Published for Free
on my Java Guides YouTube Channel

Subscribe to my YouTube Channel (165K+ subscribers):
Java Guides Channel

Top 10 My Udemy Courses with Huge Discount:
Udemy Courses - Ramesh Fadatare