Java Stream sorted() Method Tutorial

In this section, we will learn what the Stream sorted() method is and how to use it in Java.

What is Java Stream sorted() Method?

The Java Stream sorted() method is used to sort the elements in a stream.

For example, if the elements in a stream are of type integer, we can use this method to make the smallest element in the stream go first and then those that are greater come after, etc.

Note: this method is intermediate and lazy.

Java sorted() Method Syntax:

Stream<T> sorted()

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

sorted() Method Parameters:

The method has two variants:

For the first variant, it doesn’t take any argument and it will order the elements of a stream in a natural order. For example, if the elements are of type string, then they will be ordered alphabetically, etc.

For the second variant, however, the method has one parameter and that is of type Comparator which is a functional interface.

This means this second variant basically needs a reference to a method as its argument:

Here’s the signature of the method:

  • The method has two parameters and they are both of the same type as the elements in the steam.
  • The return value of this reference method is of type integer.

Inside the body of this reference method is the place where we define the instructions to be executed and result in ordering the elements of a stream.

sorted() Method Return Value:

The return value of the sorted() method for both variants is a new stream.

For the reference method that we pass as the argument of the second variant of the sorted() method, here are the possible return values:

The method takes the first and second elements in the stream as its first and second arguments and will compare them.

  • If the first argument is bigger than the second one, then the return value of this method will be 1.
  • If the first argument is less than the second one, then the return value of the method will be -1.
  • If both arguments are equal, then the return value of the method will be 0.

This process will go on for the entire elements of a stream to sort them all out.

Now, we use this technique when the purpose is to order elements naturally. For example, for integer values, the natural order is 1,2,3,4,5…

But if the purpose is to order them in a reverse order like 5,4,3,2,1… then the position of the 1 and -1 should change! Meaning if the first argument is bigger than the second one, then the value -1 should return instead of the value 1.

Example: using Stream sorted() method

import java.util.stream.Stream;
class Main{
    public static void main(String[] args) {
        Stream<Integer> stream = Stream.of(1,2,3,4,5,6,7,8,9,10,3,23,4,23,423,2,34,56,7,86,54,5);
        
        stream.sorted().forEach(e->System.out.print(e+", "));
    }
}

Output:

1, 2, 2, 3, 3, 4, 4, 5, 5, 6, 7, 7, 8, 9, 10, 23, 23, 34, 54, 56, 86, 423,

Example: Java Stream sorted() with reference method:

import java.util.stream.Stream;
class Main{
    public static void main(String[] args) {
        Stream<String> stream = Stream.of("Omid","Ellen","Jack","John","Elon","James");
        
        stream.sorted((v1,v2)-> v1.compareToIgnoreCase(v2)).forEach(e->System.out.print(e+", "));
    }
}

Output:

Ellen, Elon, Jack, James, John, Omid,

How to Sort a List in Java? (Ordered List)

Using the sorted() method, we can sort out the elements of a list object as well.

Basically, a list object has a method called stream() which produces a stream of its elements.

So we can call that stream() method and then call the sorted() method on top of it and sort the elements and then finally call the collect() method to collect the sorted elements and create another list object.

Example: sorting a list in Java

import java.util.stream.Stream;
import java.util.List;
import java.util.stream.Collectors;
class Main{
    public static void main(String[] args) {
        List<String>list = List.of("Omid","Ellen","Jack","John","Elon","James");

        List<String>listS = list.stream().sorted().collect(Collectors.toList());

        listS.forEach(e->System.out.print(e+", "));
    }
}

Output:

Ellen, Elon, Jack, James, John, Omid,

Java Sort String

Sorting a string is also relatively similar to the way we’ve sorted a list object.

Basically, String objects in Java have a method called chars() that will return the characters of a string in a form of IntStream.

Note that the IntStream does not have the sorted() method, so we need to convert the IntStream into Stream type and then use the sorted method to sort the characters of the stream.

Example: sorting a String in Java

class Main{
    public static void main(String[] args) {
        String unsorted = "dfadfrwebdnbcvmeeracxcsdferc";

        StringBuilder builder = new StringBuilder();

        unsorted.chars().mapToObj(e->(char)e).sorted().forEach(e->builder.append(e));

        String result = builder.toString();

        System.out.println(result);
    }
}

Output:

aabbccccddddeeeefffmnrrrsvwx

Leave a Reply