Home » Core Java » Java 8 Filter Null Values from a Stream Example

About Yatin

Yatin
The author is graduated in Electronics & Telecommunication. During his studies, he has been involved with a significant number of projects ranging from programming and software engineering to telecommunications analysis. He works as a technical lead in the information technology sector where he is primarily involved with projects based on Java/J2EE technologies platform and novel UI technologies.

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
(No Ratings Yet)
3 Comments Views Tweet it!

Do you want to know how to develop your skillset to become a Java Rockstar?

Subscribe to our newsletter to start Rocking right now!

To get you started we give you our best selling eBooks for FREE!

 

1. JPA Mini Book

2. JVM Troubleshooting Guide

3. JUnit Tutorial for Unit Testing

4. Java Annotations Tutorial

5. Java Interview Questions

6. Spring Interview Questions

7. Android UI Design

 

and many more ....

 

Receive Java & Developer job alerts in your Area

 

3
Leave a Reply

avatar
2 Comment threads
1 Thread replies
0 Followers
 
Most reacted comment
Hottest comment thread
3 Comment authors
AndreyYatin BatradPedro Recent comment authors
  Subscribe  
newest oldest most voted
Notify of
dPedro
Guest
dPedro

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
Guest
Andrey

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