How to sort a Stream using Java 8 and Lambda.

In Java 8, the elements of a Stream class can be sorted using a Lambda expressions without creating an anonymous comparator.


stream.sorted( (a, b) -> a.compareTo( b ) )

This example first creates a Stream of Test Objects. Each Test object has a String variable called name. This is the variable that will be used for sorting.
Then, the stream is sorted according to the object name using the sorted method.
Finally, all the elements from the Stream are written in the output using the forEach method. The calls are done sequencially on the stream. The code is simpler to understand as less code is written especialy for filtering the elements of the stream.

Create the following java file:


public class LambdaSortStream {

    public static void main(String[] argv){
        Stream<Test> stream = Stream.of( new Test("a"), new Test("c"), new Test("a"), new Test("b"), new Test("b"));
        System.out.println( "Sorted Stream: " );
        stream.sorted( (a, b) -> ) )
            .forEach( a -> {
                System.out.println( );
            } );

class Test {
    Test(String n){
        name = n;
    String name;

The output will be:

Sorted Stream: 

A lambda expression is very generic, it causes a performance impact compared with creating a java method using the same logic. Using a lambda expression allows to write smaller and simpler code. It will be easier to understand and maintain on the long run.


Lambda Expressions

Recent Comments