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
- What is a Lambda Expression?
- Sorting with Lambdas
- Complete Example Program
- 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:
- Argument list:
(parameters)
- Arrow token:
->
- 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:
-
Person Class:
- The
Person
class has attributesname
andage
with corresponding getters. - The
toString
method is overridden to provide a readable string representation ofPerson
objects.
- The
-
SortArrayObjectsWithLambdas Class:
- The
main
method demonstrates how to use lambda expressions to sort an array ofPerson
objects by theirage
andname
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.
- The
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
Post a Comment
Leave Comment