Java 8 Stream sorted()

The sorted() method is a part of the Java Stream API, which is used for processing sequences of elements in a functional style. The sorted() method is specifically used to sort the elements of a Stream based on their natural order or using a provided Comparator.

Syntax of Java 8 Stream sorted() method

There are two overloaded versions of the Java 8 Stream sorted() method.

  1. Stream<T> sorted()
  2. Stream<T> sorted(Comparator<? super T> comparator)

The first method takes no arguments and returns a new stream that contains the elements of the original stream sorted in their natural order, as determined by their Comparable interface implementation.

Here’s an example of how to use the sorted() method without any custom Comparator.

List<Integer> numbers = Arrays.asList(3, 1, 4, 1, 5, 9, 2, 6, 5, 3, 5);
List<Integer> sortedNumbers = numbers.stream().sorted().collect(Collectors.toList());
// sortedNumbers will be [1, 1, 2, 3, 3, 4, 5, 5, 5, 6, 9]

If we want to sort the elements in a custom order or based on custom criteria, we can use an overloaded version of the sorted(Comparator<? super T> comparator) method that accepts a Comparator. Here’s an example of that.

List<Person> people = Arrays.asList(
    new Person("Alice", 25),
    new Person("Bob", 30),
    new Person("Charlie", 20)
);

List<Person> sortedPeople = people.stream()
    .sorted((p1, p2) -> p1.getAge() - p2.getAge())
    .collect(Collectors.toList());
// sortedPeople will be sorted by age: [Charlie(20), Alice(25), Bob(30)]

Java 8 Stream sorted() examples

Example 1: Sorting a List of Integers

Without Java 8:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortingExample {
    public static void main(String[] args) {
        List<Integer> numbers = new ArrayList<>();
        numbers.add(3);
        numbers.add(1);
        numbers.add(4);
        numbers.add(1);
        numbers.add(5);

        Collections.sort(numbers); // Sorting without Java 8

        for (Integer number : numbers) {
            System.out.print(number + " ");
        }
    }
}

Output (Without Java 8):

1 1 3 4 5

With Java 8:

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

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

        List<Integer> sortedNumbers = numbers.stream()
            .sorted()
            .collect(Collectors.toList()); // Sorting with Java 8

        sortedNumbers.forEach(System.out::print);
    }
}

Output (With Java 8):

11435

Example 2: Sorting a List of Strings

Without Java 8:

import java.util.ArrayList;
import java.util.Collections;
import java.util.List;

public class SortingExample {
    public static void main(String[] args) {
        List<String> words = new ArrayList<>();
        words.add("banana");
        words.add("apple");
        words.add("cherry");
        words.add("date");

        Collections.sort(words); // Sorting without Java 8

        for (String word : words) {
            System.out.print(word + " ");
        }
    }
}

Output (Without Java 8):

apple banana cherry date

With Java 8:

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

public class SortingExample {
    public static void main(String[] args) {
        List<String> words = Arrays.asList("banana", "apple", "cherry", "date");

        List<String> sortedWords = words.stream()
            .sorted()
            .collect(Collectors.toList()); // Sorting with Java 8

        sortedWords.forEach(System.out::print);
    }
}

Output (With Java 8):

applebananacherrydate

Example 3: Sorting a List of Custom Objects

package com.javatute.stream;

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

class Student {
    private String name;
    private int id;

    public Student(String name, int id) {
        this.name = name;
        this.id = id;
    }

    public String getName() {
        return name;
    }

    public void setName(String name) {
        this.name = name;
    }

    public int getId() {
        return id;
    }

    public void setId(int id) {
        this.id = id;
    }
}

public class JavaStreamCustomObjectSortedExample {
    public static void main(String[] args) {
        List<Student> studentList = new ArrayList<>();
        studentList.add(new Student("Sam", 10));
        studentList.add(new Student("Jam", 12));
        studentList.add(new Student("Arya", 4));
        studentList.add(new Student("Peter", 155));
        studentList.add(new Student("James", 3));
        studentList.add(new Student("Sid", 5));
        studentList.add(new Student("Prince", 1));

        List<Student> sortStudentByName = studentList.stream().
                sorted((s1, s2)->s1.getName().compareTo(s2.getName())).collect(Collectors.toList());

        //Another way to do this using method reference
        List<Student> sortStudentByName1 = studentList.stream().
                sorted(Comparator.comparing(Student::getName)).collect(Collectors.toList());

        for (Student s : sortStudentByName) {
            System.out.println("Name is:- " + s.getName());
        }
    }
}

Output:-

Name is:- Arya
Name is:- Jam
Name is:- James
Name is:- Peter
Name is:- Prince
Name is:- Sam
Name is:- Sid

Points related to the Java 8 Stream sorted() method

  1. Sorting in Natural Order:
  • When we use the sorted() method without providing a custom Comparator, it sorts the elements of the stream in their natural order.
  • For example, for numbers, it sorts in ascending order, and for strings, it sorts in lexicographical order.
  1. Custom Sorting with Comparator:
  • We can customize the sorting order by providing a custom Comparator to the sorted() method.
  • This allows us to sort elements based on criteria other than their natural order.
  • For example, we can sort a list of custom objects based on a specific property or attribute.
  1. Immutable Operation:
  • The sorted() method does not modify the original stream. Instead, it creates and returns a new stream containing the sorted elements.
  • The original stream remains unchanged, allowing us to perform multiple operations on it without altering the order of elements.
  1. Intermediate Operation:
  • sorted() is an intermediate operation in the Stream API. It is typically followed by a terminal operation like collect(), forEach(), or another stream operation.
  • Intermediate operations are lazy, meaning they don’t perform any work until a terminal operation is invoked.
  1. Performance Considerations:
  • Sorting can be an expensive operation, especially for large data sets.
  • When using sorted(), Java may use various sorting algorithms behind the scenes, such as merge sort or TimSort, which are designed for efficiency.
  • Keep in mind that the performance of sorting can vary depending on the size and nature of the data you are sorting, so it’s essential to consider performance implications when sorting large data sets.

In summary, the sorted() method in Java 8 Streams is a valuable tool for sorting elements either in their natural order or based on custom criteria. It’s a versatile and immutable intermediate operation that allows you to efficiently work with ordered data within streams.

Objective questions related to the Java 8 Stream sorted() method

1. What is the primary purpose of the sorted() method in Java 8 Streams?

  • A) To remove duplicates from a Stream
  • B) To filter elements based on a condition
  • C) To sort elements in a Stream
  • D) To perform a mapping operation

2. When you use sorted() without providing a custom Comparator, how are elements sorted?

  • A) In reverse order
  • B) Based on their insertion order
  • C) In their natural order
  • D) In a random order

3. Which of the following is an immutable operation when using the sorted() method in Java 8 Streams?

  • A) Sorting the original stream in place
  • B) Creating a new stream with sorted elements
  • C) Reversing the order of elements in the stream
  • D) Filtering elements based on a condition

4. What is the primary difference between the natural ordering and custom ordering using sorted()?

  • A) Natural ordering is faster than custom ordering.
  • B) Natural ordering is based on a provided Comparator.
  • C) Natural ordering uses the default Comparable implementation.
  • D) Natural ordering cannot be used with the sorted() method.

5. Which of the following is an example of using a custom Comparator with sorted()?

  • A) stream.sortedBy(Comparator.naturalOrder())
  • B) stream.sorted()
  • C) stream.sorted((a, b) -> a.compareTo(b))
  • D) stream.sorted(Comparator.reverseOrder())

6. In the context of Java 8 Streams, what is the purpose of the collect() method?

  • A) To remove elements from a Stream
  • B) To create a new Stream
  • C) To transform elements in a Stream
  • D) To collect elements into a collection after stream operations

7. What kind of operation is sorted() in the Stream API?

  • A) Terminal operation
  • B) Stateless intermediate operation
  • C) Stateful intermediate operation
  • D) Parallel operation

8. Which sorting algorithm is commonly used by Java’s sorted() method for sorting elements in a Stream?

  • A) Quick Sort
  • B) Bubble Sort
  • C) Merge Sort
  • D) Insertion Sort

9. When using sorted() on a Stream of custom objects, how do you specify the sorting criteria?

  • A) By modifying the Comparable interface of the custom objects
  • B) By using the sorted() method without any arguments
  • C) By providing a custom Comparator to the sorted() method
  • D) By invoking the sortedBy() method on the Stream

10. What happens to the original Stream when you apply the sorted() method in Java 8?

  • A) The original Stream is sorted in place.
  • B) The original Stream is unchanged, and a new sorted Stream is created.
  • C) The original Stream is reversed.
  • D) The original Stream is truncated to a certain size.

Answers:

  1. C) To sort elements in a Stream
  2. C) In their natural order
  3. B) Creating a new stream with sorted elements
  4. C) Natural ordering uses the default Comparable implementation.
  5. C) stream.sorted((a, b) -> a.compareTo(b))
  6. D) To collect elements into a collection after stream operations
  7. B) Statefull intermediate operation
  8. C) Merge Sort
  9. C) By providing a custom Comparator to the sorted() method
  10. B) The original Stream is unchanged, and a new sorted Stream is created.

That’s all about the Java 8 Stream sorted() method.

Other Java 8 tutorials