Java 8 FAQ: Top Questions
23. How does the sorted() method work in Java 8 Streams?
The sorted()
method in Java 8 Streams is an intermediate operation that returns a stream with elements sorted according to their natural order or a custom comparator. It does not modify the original data source.
πΊοΈ Step-by-Step Instructions:
- Use
sorted()
with no arguments to sort elements in natural order (must be Comparable). - Use
sorted(Comparator)
to sort with custom logic. - Chain with
collect()
or other terminal operations to access sorted data.
π₯ Example Input:
List<String> names = Arrays.asList("John", "Alice", "Bob");
π Sorting with and without a Comparator:
// Natural order
List<String> sortedNames = names.stream()
.sorted()
.collect(Collectors.toList());
// Custom order (reverse)
List<String> reverseSorted = names.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
β Java 8 Solution:
import java.util.*;
import java.util.stream.*;
public class StreamSortedExample {
public static void main(String[] args) {
List<String> names = Arrays.asList("John", "Alice", "Bob");
List<String> sortedNames = names.stream()
.sorted()
.collect(Collectors.toList());
List<String> reverseSorted = names.stream()
.sorted(Comparator.reverseOrder())
.collect(Collectors.toList());
System.out.println("Sorted: " + sortedNames);
System.out.println("Reversed: " + reverseSorted);
}
}
π Output:
Sorted: [Alice, Bob, John]
Reversed: [John, Bob, Alice]
π Detailed Explanation:
- sorted(): Sorts based on natural ordering of elements (Comparable interface).
- sorted(Comparator): Allows custom sorting rules (e.g. reverse, case-insensitive).
- Sorting is stable and preserves original order for equal elements.
π οΈ Use Cases:
- Ordering display data alphabetically or numerically.
- Custom ranking and prioritization in UI or reports.
- Preparing sorted data before writing to files or databases.