How do I use sorted method in Java Stream API?

In the Java Stream API, the sorted() method is used to sort elements in a stream. The sorted() method returns a stream consisting of the elements of the original stream, sorted according to natural order. If the elements of the stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed.

Take a look at this example:

package org.kodejava.stream;

import java.util.stream.Stream;

public class SortedString {
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("d", "a", "b", "c", "e");
        stream.sorted().forEach(System.out::println);
    }
}

In this code, we create a stream of String objects and sort it using the sorted() operation. The forEach method is a terminal operation that processes the sorted stream.

If you would like to sort objects of a custom class, you may need to supply your own comparator:

package org.kodejava.stream;

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

public class SortedCustomComparator {

    public static void main(String[] args) {
        Stream<User> usersStream = Stream.of(
                new User("John", 30),
                new User("Rosa", 25),
                new User("Adam", 23));

        usersStream
                .sorted(Comparator.comparing(User::getAge))
                .forEach(System.out::println);
    }

    static class User {
        String name;
        int age;

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

        String getName() {
            return name;
        }

        int getAge() {
            return age;
        }

        @Override
        public String toString() {
            return "User{" + "name='" + name + '\'' + ", age=" + age + '}';
        }
    }
}

In this case, the sorted() method takes a Comparator argument, which is created using a lambda function. This comparator compares User objects by their ages.

In Java Stream API, you can use the sorted() and limit() methods together, but their ordering impacts performance. The sorted() method sorts all the elements in the stream, whereas limit(n) shortens the stream to be no longer than n elements in length.

If you call limit() before sorted(), like:

stream.limit(10).sorted()

The operation will only sort the first 10 elements from the stream.

But if you call sorted() before limit(), like:

stream.sorted().limit(10)

The operation will sort the entire stream, which may be much larger and more time-consuming, and then cut down the result to only keep the first 10 items.

So, if your task is to ‘find the smallest (or largest) n elements’, it is more efficient to first sort the stream and then limit it. If you want to ‘sort the first n elements’, you should limit the stream first and then sort it.

Wayan

Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.