Java Stream sorted() Example

1. Introduction

This tutorial explores the sorted() method in the Java Stream API. The sorted() method is an intermediate operation that sorts the elements of a stream into a specified order. It can use natural ordering or a provided Comparator.

Key Points

1. sorted() sorts the elements of the stream.

2. It can use natural ordering or a custom order defined by a Comparator.

3. Sorting is a common operation to prepare data for further processing, such as display or sequential analysis.

2. Program Steps

1. Create a Stream of elements.

2. Apply the sorted() method using natural ordering or a custom Comparator.

3. Collect or process the sorted stream to demonstrate its effects.

3. Code Program

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

public class StreamSortedExample {

    public static void main(String[] args) {
        // Stream of integers
        Stream<Integer> numberStream = Stream.of(5, 3, 9, 1, 4);

        // Sort the stream in natural order
        List<Integer> sortedNumbers = numberStream.sorted().collect(Collectors.toList());
        System.out.println("Sorted numbers (natural order): " + sortedNumbers);

        // Stream of strings
        Stream<String> stringStream = Stream.of("banana", "apple", "cherry", "date");

        // Sort the stream using a custom comparator
        List<String> sortedStrings = stringStream.sorted(Comparator.reverseOrder()).collect(Collectors.toList());
        System.out.println("Sorted strings (reverse order): " + sortedStrings);
    }
}

Output:

Sorted numbers (natural order): [1, 3, 4, 5, 9]
Sorted strings (reverse order): [date, cherry, banana, apple]

Explanation:

1. Stream.of(5, 3, 9, 1, 4) creates a stream of integers.

2. numberStream.sorted() sorts the integers in natural ascending order.

3. sortedNumbers.collect(Collectors.toList()) collects the sorted numbers into a list and prints them.

4. Stream.of("banana", "apple", "cherry", "date") creates a stream of strings.

5. stringStream.sorted(Comparator.reverseOrder()) sorts the strings in descending order using a reverse order comparator.

6. sortedStrings.collect(Collectors.toList()) collects the sorted strings into a list and prints them in reverse alphabetical order.

Continue Learning with Java Guides

Want to take your programming skills to the next level? Explore my practical Udemy courses on Java, Spring Boot, Microservices, Full-Stack Development, Docker, and Generative AI. You can also follow my structured learning roadmaps to become a professional developer.

By Ramesh Fadatare - Udemy Instructor Partner

Comments