The Stream.sorted()
is the method of the Stream
interface that returns a sorted stream. The elements of the stream are sorted according to their natural order or according to a provided Comparator
. The sorted stream is new and does not affect the ordering of the elements in the original stream. This method is an intermediate operation and can be chained with other Stream
operations.
The syntax of the sorted()
method is as follows:
stream.sorted()
This method does not take any parameters.
This method returns a sorted stream.
This method may throw a ClassCastException
, if the elements in the stream are not Comparable
.
The code example below shows how to use the sorted()
method:
sorted()
methodLet's look at the code below:
import java.util.*;import java.util.stream.*;class StreamExample {public static void main(String[] args){Stream<Integer> stream = Stream.of(1, 3, 2, 6, 5, 8);stream.sorted().forEach(System.out::println);}}
sorted()
method, which returns a sorted stream. The forEach()
method prints each element of the sorted stream on a new line. It is an intermediate operation and does not affect the elements in the original stream.sorted()
method with Comparator
We may use the sorted()
method to sort the elements in reverse order by passing a Comparator
as an argument. Let's look at the code below:
import java.util.*;import java.util.stream.*;class StreamExample {public static void main(String[] args){Stream<Integer> stream = Stream.of(1, 3, 2, 6, 5, 8);stream.sorted((a, b)->b-a).forEach(System.out::println);}}
sorted()
method with a custom Comparator
that sorts the elements in reverse order. We use the sorted()
method to sort objects of a user-defined class by passing a Comparator
as an argument. Let's look at the code below:
import java.util.*;import java.util.stream.*;class Employee {int id, salary;String name, designation;// constructorEmployee(int id,String name,int salary,String designation){this.id = id;this.name = name;this.salary = salary;this.designation = designation;}public String toString() {return "Employee{id=" + this.id+ ", name=\'" + this.name+ "\', salary=" + this.salary+ ", designation=\'"+ this.designation + "\'}";}}class Example {public static void main(String[] args){List<Employee> list = new ArrayList<Employee>();// adding elements to the listlist.add(new Employee(1,"John",45000,"Manager"));list.add(new Employee(2,"Martin",40000,"Developer"));list.add(new Employee(3,"Sam",35000,"tester"));// sorting the list according to the salary// in ascending orderStream<Employee> stream = list.stream();stream.sorted((e1, e2) -> e1.salary - e2.salary).forEach(System.out::println);}}
Employee
class with four fields: id
, name
, salary
, and designation
.Employee
objects and add three elements to the list.stream()
method.sorted()
method with a custom Comparator
that compares two Employee
objects by their salaries. Then, we use the forEach()
method to print each element of the sorted stream on a new line.