Streams – sorted() operation

Stream sorted() operation in Java is an intermediate operation, and it is used to sort the elements of a Stream. It accepts a stream of elements and returns a new, sorted stream. Sorting is according to the natural order.

The elements of a stream need to be Comparable. Otherwise, we’ll get the java.lang.ClassCastException when the terminal operation gets executed.

Java Stream sorted() operation – examples

Example 1

Sort the list of strings:

class Test {

  public static void main(String[] args) {
    List<String> names = new ArrayList<>(Arrays.asList("John", "Alex", "Megan", "Bobby", "Xavier"));

    List<String> orderedNames = names.stream()
            .sorted()
            .collect(Collectors.toList());

    System.out.println(orderedNames);
  }
}

Output: [Alex, Bobby, John, Megan, Xavier]

Example 2

Sort a list of customs objects.

Let’s create a Student class that implements a Comparable:

class Student implements Comparable<Student> {
  private String firstName;
  private String lastName;
  private int grade;

  public Student(String firstName, String lastName, int grade) {
    this.firstName = firstName;
    this.lastName = lastName;
    this.grade = grade;
  }

  @Override
  public String toString() {
    return "student: { firstName: " + firstName + ", lastName: " + lastName + ", grade: " + grade;
  }

  @Override
  public int compareTo(Student student) {
    if (this.grade == student.grade) {
      return 0;
    } else if (this.grade > student.grade) {
      return 1;
    } else {
      return -1;
    }
  }
}

Now let’s write a program that takes a list of students and sorts it out based on the grade field: 

class Test {

  public static void main(String[] args) {
    List<Student> sortedStudents = getStudents().stream()
            .sorted()
            .collect(Collectors.toList());

    System.out.println(sortedStudents);
  }

  private static List<Student> getStudents() {
    List<Student> students = new ArrayList<>();
    students.add(new Student("Steve", "Rogers", 8));
    students.add(new Student("John", "Doe", 5));
    students.add(new Student("Melissa", "Smith", 7));
    students.add(new Student("Megan", "Norton", 4));
    students.add(new Student("Tom", "Johnson", 9));

    return students;
  }
}

Output:

[student: { firstName: Megan, lastName: Norton, grade: 4, 
student: { firstName: John, lastName: Doe, grade: 5, 
student: { firstName: Melissa, lastName: Smith, grade: 7, 
student: { firstName: Steve, lastName: Rogers, grade: 8, 
student: { firstName: Tom, lastName: Johnson, grade: 9]

Note that the ordering was performed based on the grade field because we used that field in the compareTo() method.

I hope this tutorial was helpful to you. To learn more, check out other Java Functional Programming tutorials.

 

Leave a Reply

Your email address will not be published. Required fields are marked *