How to filter null values from a Stream using Java 8

In Java 8 with Lambda the null values from a Stream can be removed by filtering on the values that are not null.

Syntax:

stream.filter( a -> a != null )

Example:

This example, first creates a Stream with 2 null values. The Stream is first filtered on the values that are not null; then using the forEach method the remaining values are written in the output. You can see that the output doesn't have any null value.

Create the following java file:

import java.util.stream.Stream;

public class LambdaStreamFilterNull {

	public static void main(String[] argv){

		// Create an String with null values
		Stream<String> stream = Stream.of( "a", null, "c", null, "a", "b", "b");

		System.out.println( "Stream without null values:" );

		// Filter the stream
		stream.filter( a -> a != null )
			  .forEach( o -> System.out.println( o ) );
		
	}
}

The output will be:

Stream without null values:
a
c
a
b
b

References:

Lambda Expressions

Recent Comments