Get Even More Visitors To Your Blog, Upgrade To A Business Listing >>

Java Stream - sorted() With Examples

If you want to sort elements of a stream, Java Stream API provides sorted() method to do that. Actually there are two variants of sorted method with the syntax as given-

  • sorted()- Returns a stream consisting of the elements of this stream, sorted according to natural order.
  • sorted(Comparator super T> comparator)- Returns a stream consisting of the elements of this stream, sorted according to the provided Comparator.

sorted() in Java Stream is a stateful intermediate operation meaning it may incorporate state from previously seen elements when processing new elements.

sorted() method Java examples

1. Stream of integers sorted in natural order.


import java.util.Arrays;
import java.util.List;
import java.util.stream.Stream;

public class StreamSortDemo {
public static void main(String[] args) {
List numList = Arrays.asList(7, 5, 18, -11, 22, -8);
Stream sortedStream = numList.stream().sorted();
sortedStream.forEach(System.out::println);
}
}

Output


-11
-8
5
7
18
22

2. Sorting a list of strings using sorted() method of Java Stream


public class StreamSortDemo {
public static void main(String[] args) {
List strList = Arrays.asList("Mumbai", "Bangalore", "London", "Berlin", "Chicago");
strList.stream().sorted().forEach(System.out::println);
}
}

Output


Bangalore
Berlin
Chicago
London
Mumbai

3. The above examples use the sorted() method where elements of the stream are sorted using the natural ordering you can also pass the Comparator to sort as per the given Comparator. For example sorting the list of integers in reverse order.


public class StreamSortDemo {
public static void main(String[] args) {
List numList = Arrays.asList(7, 5, 18, -11, 22, -8);
numList.stream().sorted(Comparator.reverseOrder()).forEach(System.out::println);
}
}

Output


22
18
7
5
-8
-11

4. In this example we’ll see how to sort user defined class objects using sorted() method. The class whose objects are to be sorted can implement Comparable to define natural ordering.


public class Employee implements Comparable{
private String empId;
private int age;
private String name;
private char gender;
private int salary;
Employee(String empId, int age, String name, char gender, int salary){
this.empId = empId;
this.age = age;
this.name = name;
this.gender = gender;
this.salary = salary;
}
public String getEmpId() {
return empId;
}

public int getAge() {
return age;
}

public String getName() {
return name;
}

public char getGender() {
return gender;
}

public int getSalary() {
return salary;
}
@Override
public String toString() {
return "Emp Id: " + getEmpId() + " Name: "
+ getName() + " Age: " + getAge();
}
@Override
public int compareTo(Employee employee) {
return this.getName().compareTo(employee.getName());
}
}

In the compareTo() method implementation comparison is done on name so that is the natural ordering for the Employee class objects.


public class StreamSortDemo {
public static void main(String[] args) {
List empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000),
new Employee("E002", 35, "Shelly", 'F', 7000),
new Employee("E003", 40, "Remington", 'M', 5000),
new Employee("E004", 37, "Bianca", 'F', 11000),
new Employee("E005", 35, "Dominic", 'M', 7000),
new Employee("E006", 28, "Amanda", 'F', 14000));
List sortedList = empList.stream().sorted().collect(Collectors.toList());
for(Employee employee : sortedList) {
System.out.println(employee);
}
}
}

Output


Emp Id: E006 Name: Amanda Age: 28
Emp Id: E004 Name: Bianca Age: 37
Emp Id: E005 Name: Dominic Age: 35
Emp Id: E001 Name: Ram Age: 40
Emp Id: E003 Name: Remington Age: 40
Emp Id: E002 Name: Shelly Age: 35

5. Using sorted() method where Comparator is passed as an argument to sort custom objects. For example if you want the List of employees sorted by age.


public class StreamSortDemo {
public static void main(String[] args) {
List empList = Arrays.asList(new Employee("E001", 40, "Ram", 'M', 5000),
new Employee("E002", 35, "Shelly", 'F', 7000),
new Employee("E003", 40, "Remington", 'M', 5000),
new Employee("E004", 37, "Bianca", 'F', 11000),
new Employee("E005", 35, "Dominic", 'M', 7000),
new Employee("E006", 28, "Amanda", 'F', 14000));
List sortedList = empList.stream().sorted(
(e1, e2) -> e1.getAge()-e2.getAge())
.collect(Collectors.toList());
for(Employee employee : sortedList) {
System.out.println(employee);
}
}
}

Output


Emp Id: E006 Name: Amanda Age: 28
Emp Id: E002 Name: Shelly Age: 35
Emp Id: E005 Name: Dominic Age: 35
Emp Id: E004 Name: Bianca Age: 37
Emp Id: E001 Name: Ram Age: 40
Emp Id: E003 Name: Remington Age: 40

That's all for this topic Java Stream - sorted() With Examples. If you have any doubt or any suggestions to make please drop a comment. Thanks!

>>>Return to Java Advanced Tutorial Page


Related Topics

  1. Java Stream - findAny() With Examples
  2. Java Stream - Collectors.groupingBy() With Examples
  3. Java Stream - max() With Examples
  4. Java Stream API Interview Questions And Answers

You may also like-

  1. Just In Time Compiler (JIT) in Java
  2. How to Get The Inserted ID (Generated ID) in JDBC
  3. AutoBoxing And UnBoxing in Java
  4. Ternary Operator in Java With Examples
  5. Removing Spaces Between Words in a String Java Program
  6. Run Python Application in Docker Container
  7. Angular Custom Two-Way Data Binding
  8. Constructor in Python - __init__() function


This post first appeared on Altair Gate - News, please read the originial post: here

Share the post

Java Stream - sorted() With Examples

×

Subscribe to Altair Gate - News

Get updates delivered right to your inbox!

Thank you for your subscription

×