0
0
JavaHow-ToBeginner · 3 min read

How to Use Stream Sorted in Java: Simple Guide

In Java, you use stream().sorted() to sort elements of a collection in natural order or with a custom comparator. It returns a new sorted stream without modifying the original collection.
📐

Syntax

The sorted() method is used on a stream to sort its elements. You can use it in two ways:

  • stream.sorted(): sorts elements in natural order (like numbers ascending or strings alphabetically).
  • stream.sorted(Comparator): sorts elements using a custom rule you provide.
java
stream.sorted()
stream.sorted(Comparator<? super T> comparator)
💻

Example

This example shows how to sort a list of numbers in ascending order using sorted() and how to sort strings by length using a custom comparator.

java
import java.util.*;
import java.util.stream.*;

public class StreamSortedExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(5, 3, 8, 1, 9);
        List<Integer> sortedNumbers = numbers.stream()
                                             .sorted()
                                             .toList();
        System.out.println("Sorted numbers: " + sortedNumbers);

        List<String> words = Arrays.asList("apple", "banana", "pear", "kiwi");
        List<String> sortedByLength = words.stream()
                                           .sorted(Comparator.comparingInt(String::length))
                                           .toList();
        System.out.println("Words sorted by length: " + sortedByLength);
    }
}
Output
Sorted numbers: [1, 3, 5, 8, 9] Words sorted by length: [kiwi, pear, apple, banana]
⚠️

Common Pitfalls

Common mistakes when using sorted() include:

  • Expecting sorted() to change the original collection (it does not; it returns a new sorted stream).
  • Using sorted() on a stream of objects without a natural order or without providing a comparator, which causes a runtime error.
  • Forgetting to collect the sorted stream back to a list or another collection.
java
import java.util.*;
import java.util.stream.*;

public class SortedPitfall {
    public static void main(String[] args) {
        List<Object> items = Arrays.asList(new Object(), new Object());
        // This will throw ClassCastException because Object has no natural order
        // items.stream().sorted().toList(); // WRONG

        // Correct: provide a comparator
        List<Object> sortedItems = items.stream()
                                        .sorted(Comparator.comparingInt(Object::hashCode))
                                        .toList();
        System.out.println("Sorted by hashCode: " + sortedItems);
    }
}
Output
Sorted by hashCode: [java.lang.Object@15db9742, java.lang.Object@6d06d69c]
📊

Quick Reference

Remember these tips when using stream.sorted():

  • Use sorted() for natural order sorting.
  • Use sorted(Comparator) to define custom sorting rules.
  • Always collect the stream after sorting to get a usable collection.
  • The original collection remains unchanged.

Key Takeaways

Use stream.sorted() to sort elements in natural order without changing the original collection.
Provide a Comparator to sorted() for custom sorting rules.
Always collect the sorted stream to a list or other collection to use the sorted results.
Avoid sorting streams of objects without natural order unless you provide a comparator.
sorted() returns a new stream; it does not modify the source collection.