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.

Syntax:

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:

import java.util.stream.Stream;

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) -> a.name.compareTo( b.name ) )
            .forEach( a -> {
                System.out.println( a.name );
            } );
			
	}
}

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

The output will be:

Sorted Stream: 
a
a
b
b
c

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.

References:

Lambda Expressions

Share this article:

Recent Comments