Introduction
Sorting a list is a common task in programming, essential for organizing data, improving search efficiency, or preparing information for display. Traditionally, sorting was done using collections or arrays, but with the introduction of Java 8 Streams, sorting has become more flexible and concise. In this guide, we will explore how to sort a list using Java 8 Streams, covering various sorting scenarios including natural order, custom order, and sorting based on object properties.
Problem Statement
The task is to create a Java program that:
- Accepts a list of elements.
- Sorts the list using Java 8 Streams.
- Outputs the sorted list.
Example 1:
- Input:
[5, 3, 8, 1, 9] - Output:
[1, 3, 5, 8, 9]
Example 2:
- Input:
["banana", "apple", "orange", "mango"] - Output:
["apple", "banana", "mango", "orange"]
Solution Steps
- Input List: Start with a list of elements that can either be hardcoded or provided by the user.
- Sort the List (Natural Order): Use the Stream API’s
sorted()method to sort the list in natural order. - Sort the List (Custom Order): Use the
sorted(Comparator)method to sort the list based on a custom comparator. - Display the Result: Print the sorted list.
Java Program
Natural Order Sorting: Sort a List of Integers Using Streams
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java 8: Sort a List of Integers Using Streams (Natural Order)
* Author: https://www.rameshfadatare.com/
*/
public class SortListNaturalOrder {
public static void main(String[] args) {
// Step 1: Take input list
List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 9);
// Step 2: Sort the list using streams (natural order)
List<Integer> sortedNumbers = numbers.stream()
.sorted()
.collect(Collectors.toList());
// Step 3: Display the result
System.out.println("Sorted List: " + sortedNumbers);
}
}
Custom Order Sorting: Sort a List of Strings Using Streams
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java 8: Sort a List of Strings Using Streams (Custom Order)
* Author: https://www.rameshfadatare.com/
*/
public class SortListCustomOrder {
public static void main(String[] args) {
// Step 1: Take input list
List<String> fruits = Arrays.asList("banana", "apple", "orange", "mango");
// Step 2: Sort the list using streams (custom order: reverse alphabetical)
List<String> sortedFruits = fruits.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
// Step 3: Display the result
System.out.println("Sorted List: " + sortedFruits);
}
}
Sorting Objects by Property: Sort a List of Custom Objects Using Streams
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java 8: Sort a List of Custom Objects Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class SortListByProperty {
public static void main(String[] args) {
// Step 1: Take input list of custom objects
List<Person> people = Arrays.asList(
new Person("John", 25),
new Person("Alice", 30),
new Person("Bob", 22)
);
// Step 2: Sort the list using streams by age (ascending order)
List<Person> sortedPeople = people.stream()
.sorted(Comparator.comparingInt(Person::getAge))
.collect(Collectors.toList());
// Step 3: Display the result
sortedPeople.forEach(person ->
System.out.println(person.getName() + ": " + person.getAge())
);
}
}
// Custom class Person
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;
}
}
Explanation of the Programs
-
Natural Order Sorting: The first program sorts a list of integers in ascending order (natural order) using
sorted(). This is the default sorting behavior for numbers and strings in Java. -
Custom Order Sorting: The second program sorts a list of strings in reverse alphabetical order using
sorted(Comparator.reverseOrder()). This demonstrates how to customize the sorting logic with a comparator. -
Sorting Objects by Property: The third program sorts a list of custom objects (e.g.,
Person) based on a specific property (age). It usesComparator.comparingInt(Person::getAge)to define the sorting criteria, showing how to sort objects based on their attributes.
Output Example
For all methods, the output will be:
Example 1:
Input: [5, 3, 8, 1, 9]
Output: Sorted List: [1, 3, 5, 8, 9]
Example 2:
Input: ["banana", "apple", "orange", "mango"]
Output: Sorted List: [orange, mango, banana, apple]
Example 3:
Input: [Person("John", 25), Person("Alice", 30), Person("Bob", 22)]
Output:
Bob: 22
John: 25
Alice: 30
Advanced Considerations
-
Sorting with Null Values: If the list contains
nullvalues, you can useComparator.nullsFirst()orComparator.nullsLast()to handle them explicitly during sorting. -
Performance Considerations: Sorting using Streams is efficient for typical list sizes. The performance is comparable to traditional methods but offers more readability and flexibility in defining custom sorting logic.
-
Sorting Multiple Properties: You can chain comparators using
thenComparing()if you need to sort by multiple properties. For example, you can sort by age and then by name if two people have the same age.
Conclusion
This guide provides multiple methods for sorting a list using Java 8 Streams, covering natural order sorting, custom order sorting, and sorting by object properties. Java 8 Streams offer a powerful and concise way to handle sorting, making your code more readable and flexible. Depending on your specific use case, you can choose the approach that best fits your needs.