September 10, 2021

Java Stream sorted() With Examples

In this tutorial we’ll see how to use Java Stream sorted() method with the help of few examples.

Syntax of sorted() method in Java Stream API

There are two variants of sorted() method.

  1. Stream<T> sorted()- Used to sort the elements of the stream according to natural order. If the elements of this stream are not Comparable, a java.lang.ClassCastException may be thrown when the terminal operation is executed.
  2. Stream<T> sorted(Comparator<? super T> comparator)- Used to sort the elements of the stream according to the provided Comparator.

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

Let us try to understand sorted() method better with the help of some Java examples.

Sort List of integers in natural order

import java.util.List;
import java.util.stream.Collectors;

public class SortedDemo {

  public static void main(String[] args) {
    // Till Java 8
    //List<Integer> myList = Arrays.asList(11, 1, 9, 1, 4, 11, 17);
    // From Java 9
    List<Integer> myList = List.of(11, 1, 9, 1, 4, 11, 17);
    List<Integer> sortedList = myList.stream().sorted().collect(Collectors.toList());
    System.out.println(sortedList);
  }
}
Output
[1, 1, 4, 9, 11, 11, 17]

Since Integer class implements Comparable (compareTo() method) so that becomes the natural ordering for the element while sorting them using sorted() method.

Sort List of integers in reverse order

Sort List of integers in reverse order using sorted() method where Comparator is passed.

public class SortedDemo {

  public static void main(String[] args) {
    // Till Java 8
    //List<Integer> myList = Arrays.asList(11, 1, 9, 1, 4, 11, 17);
    // From Java 9
    List<Integer> myList = List.of(11, 1, 9, 1, 4, 11, 17);
    List<Integer> sortedList = myList.stream()
                     .sorted(Comparator.reverseOrder())
                     .collect(Collectors.toList());
    System.out.println(sortedList);
  }
}
Output
[17, 11, 11, 9, 4, 1, 1]

Sort List of Strings

Since String class in Java also implements Comparable interface so that becomes the natural ordering for the element while sorting them using sorted() method.

public class SortedDemo {

  public static void main(String[] args) {
    // Till Java 8
    //List<String> myList = Arrays.asList("Ram", "Madan", "Jack", "Ram", "Jack");
    // From Java 9
    List<String> myList = List.of("Ram", "Madan", "Jack", "Ram", "Jack");
    List<String> sortedList = myList.stream()
                    .sorted()
                    .collect(Collectors.toList());
    System.out.println(sortedList);
  }
}
Output
[Jack, Jack, Madan, Ram, Ram]

Sorting List of custom objects

With List containing Integers and Strings sorting doesn’t require any extra effort as both of these classes already implement Comparable defining the natural ordering. With custom objects you do need to implement Comparable and provide natural ordering.

Student class used in the example is as given below-

public class Student implements Comparable<Student> {
  private int rollNo;
  private String name;
  private String stream;
  private int marks;
  Student(int rollNo, String name, String stream, int marks){
    this.rollNo = rollNo;
    this.name = name;
    this.stream = stream;
    this.marks = marks;
  }
  public int getRollNo() {
    return rollNo;
  }
  public void setRollNo(int rollNo) {
    this.rollNo = rollNo;
  }
  public String getName() {
    return name;
  }
  public void setName(String name) {
    this.name = name;
  }

  public String getStream() {
    return stream;
  }
  public void setStream(String stream) {
    this.stream = stream;
  }
  public int getMarks() {
    return marks;
  }
  public void setMarks(int marks) {
    this.marks = marks;
  }
  @Override
  public String toString() {
    return "Roll Number: " +  getRollNo() 
        + " Name: " + getName() + " Marks: " + getMarks();
  }
  @Override
  public int compareTo(Student student) {
    return this.getName().compareTo(student.getName());
  }
}

As you can see compareTo() method implementation provides sorting on name so that is the natural ordering for the Student class objects.

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

public class SortedDemo {

  public static void main(String[] args) {
    List<Student> studentList = Arrays.asList(new Student(1, "Peter", "Science", 75),
              new Student(2, "Ram", "Science", 99),
              new Student(3, "Priscilla", "Art", 68),
              new Student(4, "Ajay", "Art", 67),
              new Student(5, "Dan", "Biology", 77));
    List<Student> sortedList = studentList.stream()
                                          .sorted()
                                          .collect(Collectors.toList());
    for(Student student: sortedList) {
      System.out.println(student);
    }  
  }
}
Output
Roll Number: 4 Name: Ajay Marks: 67
Roll Number: 5 Name: Dan Marks: 77
Roll Number: 1 Name: Peter Marks: 75
Roll Number: 3 Name: Priscilla Marks: 68
Roll Number: 2 Name: Ram Marks: 99

You can also provide your own Comparator implementation by using the sorted method that takes Comparator as an argument. For example suppose you want the List of students sorted by marks.

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

public class SortedDemo {

  public static void main(String[] args) {
    List<Student> studentList = Arrays.asList(new Student(1, "Peter", "Science", 75),
              new Student(2, "Ram", "Science", 99),
              new Student(3, "Priscilla", "Art", 68),
              new Student(4, "Ajay", "Art", 67),
              new Student(5, "Dan", "Biology", 77));
    List<Student> sortedList = studentList.stream()
                                          .sorted((s1, s2) -> s1.getMarks()-s2.getMarks())
                                          .collect(Collectors.toList());
    for(Student student: sortedList) {
      System.out.println(student);
    }  
  }
}
Output
Roll Number: 4 Name: Ajay Marks: 67
Roll Number: 3 Name: Priscilla Marks: 68
Roll Number: 1 Name: Peter Marks: 75
Roll Number: 5 Name: Dan Marks: 77
Roll Number: 2 Name: Ram Marks: 99

Sorting a Set using Java Stream sorted() method

Sorting a Set is similar to sorting a List. You can create a Stream using the Set and call the sorted() method.

import java.util.HashSet;
import java.util.Set;

public class SortedDemo {
  public static void main(String[] args) {
      Set<String> nameSet = new HashSet<>();
      nameSet.add("Ram");
      nameSet.add("Peter");
      nameSet.add("Ajay");
      nameSet.add("Priscilla");
      nameSet.add("Dan");
      
      nameSet.stream()
             .sorted()
             .forEach(System.out::println);
  }
}
Output
Ajay
Dan
Peter
Priscilla
Ram

Sorting a Map using Java Stream sorted() method

You can sort a HashMap using sorted() method too. In the following example a HashMap is sorted on its values.

import java.util.HashMap;
import java.util.LinkedHashMap;
import java.util.Map;
import java.util.stream.Collectors;

public class SortedDemo {

  public static void main(String[] args) {
    Map<Integer, String> nameMap = new HashMap<>();
      nameMap.put(1, "Ram");
      nameMap.put(2, "Peter");
      nameMap.put(3, "Ajay");
      nameMap.put(4, "Priscilla");
      nameMap.put(5, "Dan");
      
      System.out.println("-- Original Map --");
      for(Map.Entry<Integer, String> name : nameMap.entrySet()) {
        System.out.println("Key- " + name.getKey() + 
                        " Value- " + name.getValue());
      }
      
      Map<Integer, String> newMap = nameMap.entrySet()
                         .stream()
                         .sorted(Map.Entry.comparingByValue())
                         .collect(Collectors.toMap(Map.Entry::getKey, Map.Entry::getValue, 
                                  (k,v)->k, LinkedHashMap<Integer, String>::new));
      System.out.println("-- Sorted Map --");
      newMap.entrySet().forEach((e)->{System.out.println("Key- " + e.getKey() + " Value- " + e.getValue());});
  }
}
Output
-- Original Map --
Key- 1 Value- Ram
Key- 2 Value- Peter
Key- 3 Value- Ajay
Key- 4 Value- Priscilla
Key- 5 Value- Dan
-- Sorted Map --
Key- 3 Value- Ajay
Key- 5 Value- Dan
Key- 2 Value- Peter
Key- 4 Value- Priscilla
Key- 1 Value- Ram

To sort on key you can use Map.Entry.comparingByKey() method.

That's all for the topic Java Stream sorted() With Examples. If something is missing or you have something to share about the topic please write a comment.


You may also like

No comments:

Post a Comment