Swiftorial Logo
Home
Swift Lessons
Tutorials
Learn More
Career
Resources

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:

  1. Use sorted() with no arguments to sort elements in natural order (must be Comparable).
  2. Use sorted(Comparator) to sort with custom logic.
  3. 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.