Hey there!
Welcome to ClearUrDoubt.com.
In this post, we will look at removing nulls from an ArrayList in Java 8.
Using Stream API, which was introduced in Java 8, we can remove null values from an ArrayList in a simple way.
Let’s look at a sample program:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 |
package com.clearurdoubt; import java.util.ArrayList; import java.util.List; import java.util.Objects; import java.util.stream.Collectors; public class RemoveNullsFromAList { public static void main(String[] args) { // Create a list of Strings List<String> list = new ArrayList<String>(); // Add Strings to the list including nulls list.add("ONE"); list.add(null); list.add("TWO"); list.add("THREE"); list.add(null); list.add("FOUR"); System.out.println("Before removing nulls: "); // Print the original list elements list.forEach(item -> System.out.println(item)); // Retain only non-null values in the list list = list.stream().filter(Objects::nonNull).collect(Collectors.toList()); System.out.println(); System.out.println("After removing nulls: "); // Print the updated list of elements list.forEach(item -> System.out.println(item)); } } |
Output:
Happy Learning :).
Please leave a reply in case of any queries.