Filter Null Values From a Stream In Java 8

Posted By : Shakil Pathan | 30-Apr-2018

Hi Guys,

In this blog, I am going to explain you about how to filter all the null values form a Stream and collect into a List, in Java 8.

Java 8 Streams added to boost your application performance. Java 8 Streams are exceptionally well designed. It provides a different and better way of performing operations on a Collection in Java.

In the below example, we can see how to review a Stream containing null values:

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8Examples {

    public static void main(String args[]) {
        Stream<String> vehicle = Stream.of("bus", "car", null, "bike", null, "train");
        List<String> result = vehicle.collect(Collectors.toList());
        result.forEach(System.out::println);
    }
    
}
	

Output of the above program will be:

bus
car
null
bike
null
train
	

To solve it, we can use Stream.filter(x -> x!=null)

import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;

public class Java8Examples {

    public static void main(String[] args) {
        Stream<String> vehicle = Stream.of("bus", "car", null, "bike", null, "train");
        List<String> result = vehicle.filter(x -> x!=null).collect(Collectors.toList());
        result.forEach(System.out::println);
    }
    
}
	

Now, output will be:

bus
car
bike
train
	

Alternatively, we can filter with Objects::nonNull

	import java.util.List;

	List<String> result = vehicle.filter(Objects::nonNull).collect(Collectors.toList());
	

Hope, It helps!

Thanks.

About Author

Author Image
Shakil Pathan

Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .

Request for Proposal

Name is required

Comment is required

Sending message..