Remove Empty ArrayList Elements in Java
Hello, Coders in this tutorial, we will learn how to remove empty ArrayList elements in Java.
Explanation:
While accessing the array, update the element by removing empty array elements in java.
To do this we need to create an array with elements and null/empty values. So in the example below, I have created an array with two null values in it.
we will create a new ArrayList to store the values (List<String>game).
game={“GRAND”, null, “THEFT”, null, “AUTO”,”V” }
Now we will use removeIf() method : The removeIf() method is used to remove all those elements from Array which satisfies a given predicate filter condition passed as a parameter to the method.
and we will also use Objects.isNull(), So what this method will do is remove any null/empty values in an array.
Now we get our final results.
Final result [GRAND, THEFT, AUTO, V]
Program to Remove Empty/Null ArrayList Elements in Java
import java.util.Arrays; import java.util.List; import java.util.ArrayList; import java.util.Objects; class Main { // Program to remove null values from a list in Java 8 public static void main(String args[]) { List<String> game = new ArrayList<>( Arrays.asList("GRAND", null, "THEFT", null, "AUTO","V")); // using removeIf() + Objects.isNull() game.removeIf(Objects::isNull); System.out.println(game); } }
INPUT:
{"GRAND", null, "THEFT", null, "AUTO","V" }
OUTPUT:
[GRAND, THEFT, AUTO, V]
You may also read:
Leave a Reply