Introduction
Handling null values in a list is a common task in Java programming, especially when working with data that might be incomplete or include optional fields. Null values can lead to NullPointerException
s if not handled properly, so it’s often necessary to clean up a list by removing these null entries. Java 8 introduced the Stream API, which provides a simple and effective way to filter out null values from a list. In this guide, we’ll explore how to remove null values from a list using Java 8 Streams, covering various use cases including lists of primitive types and custom objects.
Table of Contents
- Problem Statement
- Solution Steps
- Java Program
- Removing Null Values from a List of Strings
- Removing Null Values from a List of Integers
- Removing Null Values from a List of Custom Objects
- Advanced Considerations
- Conclusion
Problem Statement
The task is to create a Java program that:
- Accepts a list of elements.
- Removes all null values from the list.
- Outputs the cleaned list.
Example 1:
- Input: List of strings
["apple", null, "orange", null, "banana"]
- Output: List of strings
["apple", "orange", "banana"]
Example 2:
- Input: List of integers
[1, null, 3, 4, null, 6]
- Output: List of integers
[1, 3, 4, 6]
Solution Steps
- Input List: Start with a list of elements that can either be hardcoded or provided by the user.
- Remove Null Values Using Streams: Use the
filter()
method to filter out null values from the list. - Display the Result: Print the cleaned list.
Java Program
Removing Null Values from a List of Strings
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java 8 - Remove Null Values from a List of Strings Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class RemoveNullValuesFromStrings {
public static void main(String[] args) {
// Step 1: Take input list
List<String> fruits = Arrays.asList("apple", null, "orange", null, "banana");
// Step 2: Remove null values from the list
List<String> cleanedList = fruits.stream()
.filter(fruit -> fruit != null)
.collect(Collectors.toList());
// Step 3: Display the result
System.out.println("Cleaned list: " + cleanedList);
}
}
Output
Cleaned list: [apple, orange, banana]
Explanation
- The
stream()
method is used to create a stream from the list of strings. - The
filter(fruit -> fruit != null)
method removes all null values from the stream. - The
collect(Collectors.toList())
method collects the non-null elements into a new list. - The resulting list
["apple", "orange", "banana"]
is printed to the console.
Removing Null Values from a List of Integers
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java 8 - Remove Null Values from a List of Integers Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class RemoveNullValuesFromIntegers {
public static void main(String[] args) {
// Step 1: Take input list
List<Integer> numbers = Arrays.asList(1, null, 3, 4, null, 6);
// Step 2: Remove null values from the list
List<Integer> cleanedList = numbers.stream()
.filter(number -> number != null)
.collect(Collectors.toList());
// Step 3: Display the result
System.out.println("Cleaned list: " + cleanedList);
}
}
Output
Cleaned list: [1, 3, 4, 6]
Explanation
- The
stream()
method is used to create a stream from the list of integers. - The
filter(number -> number != null)
method removes all null values from the stream. - The
collect(Collectors.toList())
method collects the non-null elements into a new list. - The resulting list
[1, 3, 4, 6]
is printed to the console.
Removing Null Values from a List of Custom Objects
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
/**
* Java 8 - Remove Null Values from a List of Custom Objects Using Streams
* Author: https://www.rameshfadatare.com/
*/
public class RemoveNullValuesFromCustomObjects {
public static void main(String[] args) {
// Step 1: Take input list of custom objects
List<Student> students = Arrays.asList(
new Student("Raj", 25),
null,
new Student("Anita", 30),
null,
new Student("Vikram", 22)
);
// Step 2: Remove null values from the list
List<Student> cleanedList = students.stream()
.filter(student -> student != null)
.collect(Collectors.toList());
// Step 3: Display the result
cleanedList.forEach(student ->
System.out.println(student.getName() + ": " + student.getAge())
);
}
}
// Custom class Student
class Student {
private String name;
private int age;
public Student(String name, int age) {
this.name = name;
this.age = age;
}
public String getName() {
return name;
}
public int getAge() {
return age;
}
}
Output
Raj: 25
Anita: 30
Vikram: 22
Explanation
- The list of
Student
objects is processed to remove all null values. - The
filter(student -> student != null)
method removes null values from the stream. - The
collect(Collectors.toList())
method collects the non-null elements into a new list. - The resulting list, containing only non-null
Student
objects, is printed to the console.
Advanced Considerations
-
Using Method References: You can also use
Objects::nonNull
as a method reference to filter out null values more concisely:List<String> cleanedList = list.stream() .filter(Objects::nonNull) .collect(Collectors.toList());
-
Immutable Lists: If the list you are working with is immutable (e.g., created with
List.of()
), removing null values requires creating a new list. Streams handle this seamlessly by creating a new collection with only non-null values. -
Handling Nested Nulls: If you have a list of objects where some fields may be null, you might need to filter based on the presence of these fields as well:
List<Student> cleanedList = students.stream() .filter(student -> student != null && student.getName() != null) .collect(Collectors.toList());
Conclusion
This guide provides methods for removing null values from a list using Java 8 Streams, covering both simple lists like strings and integers, as well as more complex lists like custom objects. Java 8 Streams offer a powerful and concise way to clean up your collections, making your code more readable and maintainable. Depending on your specific use case, you can easily apply the techniques demonstrated in this guide to remove null values from any list.