Introduction
Sorting a list is a common operation in many applications. In Java 8, the Stream API introduced an easy and functional way to sort lists using the sorted()
method. The sorted()
method can be used with or without a custom comparator, depending on the sorting criteria you need. This makes sorting more intuitive and allows you to handle complex sorting logic in a concise way.
In this guide, we will learn how to sort a list using streams in Java 8, with examples of sorting in natural order and with custom comparators.
Solution Steps
- Define the List: Create a list of elements (e.g., integers or strings) that need to be sorted.
- Convert the List to a Stream: Use the
stream()
method to convert the list to a stream. - Use
sorted()
: Apply thesorted()
method for sorting, either in natural order or with a custom comparator. - Collect the Stream: Collect the sorted elements back into a list using
collect(Collectors.toList())
. - Display the Result: Print or use the sorted list.
Java Program
Example 1: Sort a List of Integers in Natural Order
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SortListWithStream {
public static void main(String[] args) {
// Step 1: Define the List of integers
List<Integer> numbers = Arrays.asList(5, 1, 4, 2, 3);
// Step 2: Convert the List to a Stream and sort in natural order
List<Integer> sortedNumbers = numbers.stream()
.sorted() // Step 3: Sort in natural order
.collect(Collectors.toList()); // Step 4: Collect back to List
// Step 5: Display the sorted List
System.out.println(sortedNumbers); // Output: [1, 2, 3, 4, 5]
}
}
Output
[1, 2, 3, 4, 5]
Explanation
Step 1: Define the List
We define a list of integers:
List<Integer> numbers = Arrays.asList(5, 1, 4, 2, 3);
Step 2: Convert the List to a Stream
We use the stream()
method to convert the list into a stream:
numbers.stream();
Step 3: Use sorted()
for Natural Order Sorting
The sorted()
method sorts the elements in their natural order (ascending order for numbers):
.sorted();
Step 4: Collect the Stream Back to a List
We use Collectors.toList()
to collect the sorted elements back into a list:
.collect(Collectors.toList());
Step 5: Display the Result
We print the sorted list:
System.out.println(sortedNumbers);
Example 2: Sort a List of Strings in Natural Order
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SortStringList {
public static void main(String[] args) {
// Step 1: Define the List of strings
List<String> words = Arrays.asList("Banana", "Apple", "Mango", "Orange");
// Step 2: Convert the List to a Stream and sort in natural order
List<String> sortedWords = words.stream()
.sorted() // Step 3: Sort strings in natural order
.collect(Collectors.toList()); // Step 4: Collect back to List
// Step 5: Display the sorted List
System.out.println(sortedWords); // Output: [Apple, Banana, Mango, Orange]
}
}
Output
[Apple, Banana, Mango, Orange]
Explanation
Step 1: Define the List
We define a list of strings:
List<String> words = Arrays.asList("Banana", "Apple", "Mango", "Orange");
Step 2: Convert the List to a Stream
We convert the list to a stream:
words.stream();
Step 3: Use sorted()
for Natural Order Sorting
We apply sorted()
to sort the strings alphabetically:
.sorted();
Step 4: Collect the Stream Back to a List
We collect the sorted strings into a list:
.collect(Collectors.toList());
Step 5: Display the Result
We print the sorted list of strings:
System.out.println(sortedWords);
Example 3: Sort a List of Custom Objects by a Field
You can also sort a list of custom objects by a specific field using the sorted()
method with a custom comparator.
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
public class SortCustomObjects {
public static void main(String[] args) {
// Step 1: Define a list of Employee objects
List<Employee> employees = Arrays.asList(
new Employee("Ravi", 30),
new Employee("Amit", 25),
new Employee("Pooja", 35)
);
// Step 2: Convert the List to a Stream and sort by age
List<Employee> sortedEmployees = employees.stream()
.sorted((e1, e2) -> Integer.compare(e1.getAge(), e2.getAge())) // Step 3: Sort by age
.collect(Collectors.toList()); // Step 4: Collect back to List
// Step 5: Display the sorted List
sortedEmployees.forEach(System.out::println); // Output: Amit:25, Ravi:30, Pooja:35
}
}
// Custom Employee class
class Employee {
private String name;
private int age;
public Employee(String name, int age) {
this.name = name;
this.age = age;
}
public int getAge() {
return age;
}
public String toString() {
return name + ":" + age;
}
}
Output
Amit:25
Ravi:30
Pooja:35
Explanation
Step 1: Define the List of Custom Objects
We define a list of Employee
objects with a name and age:
List<Employee> employees = Arrays.asList(
new Employee("Ravi", 30),
new Employee("Amit", 25),
new Employee("Pooja", 35)
);
Step 2: Convert the List to a Stream
We convert the list to a stream:
employees.stream();
Step 3: Use sorted()
with a Custom Comparator
We sort the employees by their age using a lambda expression in the sorted()
method:
.sorted((e1, e2) -> Integer.compare(e1.getAge(), e2.getAge()));
Step 4: Collect the Stream Back to a List
We collect the sorted list of employees back into a list:
.collect(Collectors.toList());
Step 5: Display the Result
We print the sorted list of employees:
sortedEmployees.forEach(System.out::println);
Conclusion
In Java 8, sorting a list using streams is simple and efficient. You can sort in natural order using the sorted()
method or create custom comparators to handle complex sorting scenarios, such as sorting objects by specific fields. The Stream API makes the sorting process more readable and concise, offering a functional approach to handling collections.
Comments
Post a Comment
Leave Comment