Core Java

Java 8 Filter Null Values from a Stream Example

Hello readers, in this tutorial, we will learn how to filter the null elements from a Stream in Java.

1. Introduction

Java Stream is a sequence of elements that support the sum operations. In streams, the elements are reckoned on demand from different data sources such as Collections, Arrays or I/O resources and thus the elements are never stored.

Streams allow the chaining of multiple operations and thus, developers can apply filtering, mapping, matching, searching, sorting or reducing operations on streams. Unlike collections which use the external iteration fashion, streams are internally iterated.

1.1 Java Stream Filter

java.util.stream.Stream.filter() method is a middle operation which returns the stream elements that matches the given predicate. Do note, a predicate is a method which returns a Boolean value. In Java, if any null value is present in a stream, then the stream operations will throw a NullPointerException. Developers can filter the null values from the stream either by using the Lambda expression,

stream.filter(str -> str != null);

or using the static nonNull() method provided by the java.util.Objects class. This method returns true if the allocated reference is not null, otherwise false. The static method is executed in two ways i.e.

  • Using Lambda expression

Code Snippet

stream.filter(str -> Objects.nonNull(str));
  • Using Method reference

Code Snippet

stream.filter(Objects::nonNull());

Now, open up the Eclipse Ide and we will go over these methods to filter the null values from a stream in Java 8.

2. Java 8 Filter Null Values from a Stream Example

2.1 Tools Used

We are using Eclipse Oxygen, JDK 1.8 and Maven.

2.2 Project Structure

Firstly, let’s review the final project structure if you’re confused about where you should create the corresponding files or folder later!

Fig. 1: Application Project Structure
Fig. 1: Application Project Structure

2.3 Project Creation

This section will show how to create a Java-based Maven project with Eclipse. In Eclipse IDE, go to File -> New -> Maven Project.

Fig. 2: Create Maven Project
Fig. 2: Create Maven Project

In the New Maven Project window, it will ask you to select project location. By default, ‘Use default workspace location’ will be selected. Select the ‘Create a simple project (skip archetype selection)’ check-box and just click on next button to proceed.

Fig. 3: Project Details
Fig. 3: Project Details

It will ask you to ‘Enter the group and the artifact id for the project’. We will input the details as shown in the below image. The version number will be by default: 0.0.1-SNAPSHOT.

Fig. 4: Archetype Parameters
Fig. 4: Archetype Parameters

Click on Finish and the creation of a maven project is completed. If you see, it has downloaded the maven dependencies and a pom.xml file will be created. It will have the following code:

pom.xml

<project xmlns="http://maven.apache.org/POM/4.0.0" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xsi:schemaLocation="http://maven.apache.org/POM/4.0.0 http://maven.apache.org/xsd/maven-4.0.0.xsd">
	<modelVersion>4.0.0</modelVersion>
	<groupId>Java8FilterNullfromStream</groupId>
	<artifactId>Java8FilterNullfromStream</artifactId>
	<version>0.0.1-SNAPSHOT</version>
	<packaging>jar</packaging>
</project>

Developers can start adding the dependencies that they want. Let’s start building the application!

3. Application Building

Below are the steps involved in explaining this tutorial.

3.1 Java Class Implementation

Let’s create the required Java files. Right-click on the src/main/java folder, New -> Package.

Fig. 5: Java Package Creation
Fig. 5: Java Package Creation

A new pop window will open where we will enter the package name as: com.jcg.java

Fig. 6: Java Package Name (com.jcg.java)
Fig. 6: Java Package Name (com.jcg.java)

Once the package is created in the application, we will need to create the implementation class to show the removal of null elements from a Stream using the java.util.stream.Stream.filter() method. Right-click on the newly created package: New -> Class.

Fig. 7: Java Class Creation
Fig. 7: Java Class Creation

A new pop window will open and enter the file name as: FilterNullValueDemo. The implementation class will be created inside the package: com.jcg.java.

Fig. 8: Java Class (FilterNullValueDemo.java)
Fig. 8: Java Class (FilterNullValueDemo.java)

3.1.1 Example of Sorting a Map in Java8

Here is the complete Java program to see how developers can filter the null elements from a Stream. Do note:

  • We start by creating a list of string elements
  • We add null values to the list along with some string elements
  • We define a boolean condition and we use it to filter out the elements
  • We Apply filter to remove the null elements
  • We retrieve the filtered stream (having all non-null elements) and we print each element of the new list

Let’s see the simple code snippet that shows this implementation.

FilterNullValueDemo.java

package com.jcg.java;

import java.util.ArrayList;
import java.util.List;
import java.util.Objects;
import java.util.stream.Collectors;

/*
 * Java program to filter the null values from a Stream in Java8
 * 
 * @author Batra, Yatin
 */
public class FilterNullValueDemo {

	public static void main(String[] args) {

		List<String> cList = new ArrayList<String>();
		cList.add("United States of America");
		cList.add("Ecuador");
		cList.add("Denmark");
		cList.add(null);
		cList.add("Seychelles");
		cList.add("Germany");
		cList.add(null);

		System.out.println("<!-----Original list with null values-----!>");		
		System.out.println(cList + "\n");

		// EXAMPLE #1 = Filter Null Values from a Stream Using 'Lambda Expressions'
		List<String> result = cList.stream().filter(str -> str != null && str.length() > 0).collect(Collectors.toList());
		System.out.println("<!-----Result after null values filtered-----!>");
		System.out.println(result + "\n");

		// EXAMPLE #2 = Filter Null Values from a Stream Using 'Method Reference'
		List<String> nonNullResult = cList.stream().filter(Objects::nonNull).collect(Collectors.toList());
		System.out.println("<!-----Result after null values filtered using nonNull-----!>");
		System.out.println(nonNullResult + "\n");

		// EXAMPLE #3 = Filter Null Values after Map intermediate operation
		List<String> mapNullResult = cList.stream().map(s -> s).filter(str -> str != null && str.length() > 0).collect(Collectors.toList());
		System.out.println("<!-----Result after null values filtered using Map intermediate operation-----!>");
		System.out.println(mapNullResult);
	}
}

4. Run the Application

To run the application, developers need to right-click on the class, Run As -> Java Application. Developers can debug the example and see what happens after every step!

Fig. 9: Run Application
Fig. 9: Run Application

5. Project Demo

The above code shows the following logs as output.

# Logs for 'FilterNullValueDemo' #
==================================
<!-----Original list with null values-----!>
[United States of America, Ecuador, Denmark, null, Seychelles, Germany, null]

<!-----Result after null values filtered-----!>
[United States of America, Ecuador, Denmark, Seychelles, Germany]

<!-----Result after null values filtered using nonNull-----!>
[United States of America, Ecuador, Denmark, Seychelles, Germany]

<!-----Result after null values filtered using Map intermediate operation-----!>
[United States of America, Ecuador, Denmark, Seychelles, Germany]

That’s all for this post. Happy Learning!

6. Conclusion

In this tutorial, we had an in-depth look at the Java8 java.util.stream.Stream.filter() method to remove the null elements from a Stream. Developers can download the sample application as an Eclipse project in the Downloads section. I hope this article served you with whatever developers are looking for.

7. Download the Eclipse Project

This was an example of filtering the null elements from a Stream in Java8.

Download
You can download the full source code of this example here: Java8FilterNullfromStream

Yatin

An experience full-stack engineer well versed with Core Java, Spring/Springboot, MVC, Security, AOP, Frontend (Angular & React), and cloud technologies (such as AWS, GCP, Jenkins, Docker, K8).
Subscribe
Notify of
guest

This site uses Akismet to reduce spam. Learn how your comment data is processed.

5 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
dPedro
dPedro
6 years ago

Seriously? A wall of text about what can be narrowed down to 3 lines of code and few sentences of commentary? This is what you do for living?

Andrey
Andrey
5 years ago

Thanks for the article
You seem to have an error in your code:
Objects::nonNull()?
Objects::nonNull

Guest
Guest
4 years ago
Reply to  Andrey

To be clear, it’s (still) wrong in the snippet, not in the full code

Hector Ccasani
Hector Ccasani
4 years ago

What happens if the ‘filter’ does not let any item on the list go through? That is, all are null. What about the rest of the pipeline?

Back to top button