Stream sorted() in Java

Java 8Object Oriented ProgrammingProgramming

The Stream sorted() in Java returns a stream consisting of the elements of this stream, sorted according to natural order.

Following is the syntax −

Stream<T> sorted()

Here, Stream is an interface in java.util.stream and <T> is the type parameter in stream. This method returns the new stream.

Following is an example to implement the sorted() method in stream class −

Example

import java.util.*;
public class Demo {
   public static void main(String[] args) {
      List<String> list = Arrays.asList("Jack", "Tom", "Kevin", "David", "Tim", "Nathan", "John", "Ryan", "Robbie");
      System.out.println("Sorted stream... ");
      list.stream().sorted().forEach(System.out::println);
   }
}

Output

The sorted stream is :
David
Jack
John
Kevin
Nathan
Robbie
Ryan
Tim
Tom

Example

Let us see another example to sort stream −

import java.util.stream.Stream;
public class Demo {
   public static void main(String[] args) {
      Stream<Integer> stream = Stream.of(50, 20, 12, 30, 5, 10, 15, 35, 60);
      System.out.println("Sorted stream..");
      stream.sorted().forEach(System.out::println);
   }
}

Output

Sorted stream..
5
10
12
15
20
30
35
50
60
raja
Published on 24-Sep-2019 12:13:06
Advertisements