How to sort a Java8 stream in reverse order? – Detailed Guide

The Java 8 Stream is a sequence of elements supporting sequential and parallel operations composed into a stream pipeline.

You can use stream().sorted((a, b) -> (b - a)) function to sort and reverse the order of Java 8 Stream

In this tutorial, you will learn different ways to sort a Java 8 Stream and return a reversed stream in detail.

Reverse Stream of Numbers using stream().sorted()

The Java 8 Stream provides .sorted() function which accepts a Comparator to compare stream elements.
To sort a stream and reverse the order of elements,

  • Convert the list to a stream of elements using the list.stream() function.
  • Invoke sorted() method of stream() with a comparator() value to convey the type of sorting.
  • Use a predefined comparator reverse function(Comparator.reverseOrder()) or lambda function((a, b) -> (b - a)) to reverse, both produce the same result.
  • Convert the sorted stream again to a list using .collect(Collectors.toList()).

Code

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

    //main
    List<Integer> numbers = Arrays.asList(4, 6,1, 3, 8, 5, 7, 9, 2, 10, 5);  
    System.out.println(numbers); //[4, 6, 1, 3, 8, 5, 7, 9, 2, 10, 5]

    List<Integer> reversedNumbers = numbers.stream().sorted((a, b) -> (b - a)).collect(Collectors.toList());  
    System.out.println(reversedNumbers);  //[10, 9, 8, 7, 6, 5, 5, 4, 3, 2, 1]

The below example demonstrates another way of using the comparator to produce the same result.

    List<Integer> reversedNumbers = numbers.stream().sorted(Comparator.reverseOrder()).collect(Collectors.toList());  
    System.out.println(reversedNumbers);  //[10, 9, 8, 7, 6, 5, 5, 4, 3, 2, 1]

Reverse Stream of Objects using stream().sorted()

To sort and reverse a stream of Objects,

  • Convert the list to a stream of elements using the list.stream() function.
  • Invokestream().sorted() with a comparator value(Comparator.comparing(Student::getName)) specifying the property of the Object to be used for comparison(sort).
  • Now reverse the comparator result using .reversed() to produce elements to be sorted in reverse order.
  • Convert the stream of elements to a List using the .collect() method.

Code

    import lombok.Builder;  
    import lombok.Data;

    //Student.java
    @Data  
    @Builder  
    public class Student {  
        String name;  
        long id;  
    }

    import com.techmam.model.Student
    import java.util.Arrays;  
    import java.util.Comparator;  
    import java.util.List;  
    import java.util.stream.Collectors;

    //main
    List<Student> students = Arrays.asList(Student.builder().id(101).name("Jessica").build(),
                                           Student.builder().id(102).name("Bala").build(),
                                           Student.builder().id(201).name("Madhan").build(),
                                           Student.builder().id(202).name("Priya").build());  

    System.out.println(students);  //[Student(name=Jessica, id=101), Student(name=Bala, id=102), Student(name=Madhan, id=201), Student(name=Priya, id=202)]

    List<Student> reversedStudents= students.stream().sorted(Comparator.comparing(Student::getName).reversed()).collect(Collectors.toList());  
    System.out.println(reversedStudents);  //[Student(name=Priya, id=202), Student(name=Madhan, id=201), Student(name=Jessica, id=101), Student(name=Bala, id=102)]

Reverse Stream of String with Null Values

To sort a List with null values and reverse the stream of elements,

  • Convert the list to a stream of elements using list.stream().
  • Invokestream().sorted() with a comparator value(Comparator.nullsLast()) to compare and sort the stream. The .nullsLast() method will move all the null values to the end of the stream.
  • Use the comparator sort type(Comparator.reverseOrder()) to reverse the stream.
  • Convert the stream to a List using the .collect() method.

Use this method to move the null values to either the first or end of the list

Code

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

    //main
    List<String> mobileBrands = Arrays.asList("Apple","Samsung",null,"Nokia","Motorola",null,"Lenovo","Huawei");  
    List<String> reversedMobileBrands = mobileBrands.stream().sorted(Comparator.nullsLast(Comparator.reverseOrder())).collect(Collectors.toList());  
    System.out.println(reversedMobileBrands);  //[Samsung, Nokia, Motorola, Lenovo, Huawei, Apple, null, null]

Use the below comparator function to move all the null values to the beginning of the List.

    List<String> mobileBrands = Arrays.asList("Apple","Samsung",null,"Nokia","Motorola",null,"Lenovo","Huawei");  
    List<String> reversedMobileBrandsNullFirst = mobileBrands.stream().sorted(Comparator.nullsFirst(Comparator.reverseOrder())).collect(Collectors.toList());  
    System.out.println(reversedMobileBrandsNullFirst);  //[null, null, Samsung, Nokia, Motorola, Lenovo, Huawei, Apple]

Related Topics

Leave a Comment