Java Streams sorted() Method with Examples

The sorted() method in Java Streams is used to sort elements of a stream in either natural order or using a custom comparator.

Syntax of sorted()

Java provides two overloaded versions of the sorted() method:

Stream<T> sorted(); 

Sorts elements in natural order (ascending for numbers, alphabetically for strings).

Stream<T> sorted(Comparator<? super T> comparator);  

Sorts elements using a custom comparator.

Sorting Primitive Data Types

Example: Sorting a List of Integers

import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;

public class StreamSortedExample {
    public static void main(String[] args) {
        List<Integer> numbers = Arrays.asList(5, 2, 8, 1, 3);

        // Sorting in natural order (ascending)
        List<Integer> sortedNumbers = numbers.stream()
                                             .sorted()
                                             .collect(Collectors.toList());

        System.out.println(sortedNumbers); // Output: [1, 2, 3, 5, 8]
    }
}

Since Integers implement Comparable, sorted() automatically sorts them in ascending order.

Example: Sorting in Descending Order

For reverse order, use Comparator.reverseOrder():

import java.util.Comparator;

List<Integer> sortedDescending = numbers.stream()
                                        .sorted(Comparator.reverseOrder()) 
                                        .collect(Collectors.toList());

System.out.println(sortedDescending); // Output: [8, 5, 3, 2, 1]

Sorting Strings

Example: Alphabetical Order

List<String> names = Arrays.asList("John", "Alice", "Bob");
List<String> sortedNames = names.stream()
                                .sorted()
                                .collect(Collectors.toList());

System.out.println(sortedNames); // Output: [Alice, Bob, John]

Example: Reverse Alphabetical Order

List<String> sortedDescending = names.stream()
                                     .sorted(Comparator.reverseOrder())
                                     .collect(Collectors.toList());

System.out.println(sortedDescending); // Output: [John, Bob, Alice]

Sorting Custom Objects

If you have a list of objects, sorting requires a Comparator.

Example: Sorting Employees by Age

import java.util.*;

class Employee {
    String name;
    int age;

    Employee(String name, int age) {
        this.name = name;
        this.age = age;
    }

    public String toString() {
        return name + " (" + age + ")";
    }
}

public class ObjectSorting {
    public static void main(String[] args) {
        List<Employee> employees = Arrays.asList(
            new Employee("John", 25),
            new Employee("Alice", 30),
            new Employee("Bob", 22)
        );

        // Sorting by age (ascending)
        List<Employee> sortedEmployees = employees.stream()
                                                  .sorted(Comparator.comparing(e -> e.age))
                                                  .collect(Collectors.toList());

        System.out.println(sortedEmployees);
    }
}

Output:

Bob (22)
John (25)
Alice (30)

Sorting by Multiple Fields (Age then Name)

List<Employee> sortedByAgeThenName = employees.stream()
                                              .sorted(Comparator.comparing(Employee::age)
                                                                .thenComparing(Employee::name))
                                              .collect(Collectors.toList());

First sorts by age, and if ages are the same, sorts by name.

Sorting in Parallel Streams

Parallel streams do not guarantee order, but sorted() forces ordering.

List<Integer> sortedParallel = numbers.parallelStream()
                                      .sorted()
                                      .collect(Collectors.toList());

System.out.println(sortedParallel); // Output: [1, 2, 3, 5, 8]

Even in parallel streams, sorted() ensures sorted output.

Sorting Large Collections Efficiently

For large datasets, sorting with parallel streams can improve performance.

List<Employee> sortedParallel = employees.parallelStream()
                                         .sorted(Comparator.comparing(Employee::age))
                                         .collect(Collectors.toList());

Note : Use parallel streams only when handling large datasets to optimize performance.

Summary

  • sorted() without argumentsNatural order sorting
  • sorted(Comparator.reverseOrder())Reverse order sorting
  • sorted(Comparator.comparing(...))Sorting objects by fields
  • Use .thenComparing() for multi-level sorting
  • Parallel streams can speed up sorting, but order is enforced only when sorted() is used

Related Posts

Leave a Reply

Your email address will not be published. Required fields are marked *