Java Streams - Stream sorted() example








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

Syntax

sorted has the following syntax.

Stream<T> sorted()

Example

The following example shows how to use sorted.

import java.util.Arrays;
import java.util.List;
//  www  .  ja  v a  2  s .  c  o m
public class Main {
  public static void main(String[] args) {
    List<String> stringList = Arrays.asList("5","1","2","3","4");

    stringList.stream()
           .sorted()
           .forEach(System.out::println);
  }
}

The code above generates the following result.