Categories
collections java

sorting operations in java using streams

In this example, we learn sorting operations in java using streams

In Java 8 it is easy to sort records from an arraylist

Streams API providing powerful features to sort the records from a list without modifying it

This will returns a stream consisting of the sorted elements

Syntax

Stream sorted()
list.stream().sorted({operations});

Ascending Example

import java.util.ArrayList;
import java.util.List;

public class AscendingSortingStreams {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("Ball");
        list.add("Apple");
        list.add("Cat"); // printitng values before sorting
        System.out.println("Values before sorting ");
        list.stream().forEach(x -> System.out.println(x));
        System.out.println("*** Values After sorting ***");
        list.stream().sorted().forEach(x -> System.out.println(x));
    }
}

Output

Values before sorting 
Ball
Apple
Cat
*** Values After  sorting ***
Apple
Ball
Cat

Descending Example

import java.util.ArrayList;
import java.util.Comparator;
import java.util.List;

public class DescendingSortingStreams {
    public static void main(String[] args) {
        List list = new ArrayList();
        list.add("Ball");
        list.add("Apple");
        list.add("Cat");
        // printitng values before sorting
        System.out.println("Values before sorting ");
        list.stream().forEach(x -> System.out.println(x));
        System.out.println("*** Values After sorting ***");
        // Comparator.reverseOrder() will sort the records in descending order
        list.stream().sorted(Comparator.reverseOrder()).forEach(x -> System.out.println(x));
    }
}

Output

Values before sorting 
Ball
Apple
Cat
*** Values After  sorting ***
Cat
Ball
Apple

References

Oracle Docs

Related Articles

filter operations in streams on java 

Iterate list using streams in java

Leave a Reply

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