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.
Cookies are important to the proper functioning of a site. To improve your experience, we use cookies to remember log-in details and provide secure log-in, collect statistics to optimize site functionality, and deliver content tailored to your interests. Click Agree and Proceed to accept cookies and go directly to the site or click on View Cookie Settings to see detailed descriptions of the types of cookies and choose whether to accept certain cookies while on the site.
About Author
Shakil Pathan
Shakil is an experienced Groovy and Grails developer . He has also worked extensively on developing STB applications using NetGem .