Today we will learn How to I Remove Null Elements From An ArrayList In Java? It can be done either by Iterator or simply by using remove if and passing a predicate.
Ways Remove Null Values From A Array List
There are ways to perform it and here we will discuss both of them one by one where we have to remove all the null values from a list or we can say all the elements which are string nothing or we can say empty elements.
Using Iterator
It is a way where we will iterate the whole array list one by one means all the elements of the arraylist one by one check the condition Whenever we find a null value just perform a removal of it. In this way, we can remove all the null values let’s see how it works.
for (Iterator<String> itr = words.iterator(); itr.hasNext(); ) { if (itr.next().isBlank()) { itr.remove(); } } // while-loop version Iterator<String> itr = words.iterator(); while (itr.hasNext()) { if (itr.next().isBlank()) { itr.remove(); } }
Here we can see how each element is checked and then removal takes place.
Now let’s understand another method
Remove If And Passing A Predicate
In this, we have used an inbuild function removeif() which removes all the spaces in between two elements or we can say if there are any blank elements it will remove them and it continues to do so until it comes to an end.
words.removeIf(new Predicate<>() { @Override public boolean test(String word) { return word.isBlank(); } }); // lambda "block" version words.removeIf(word -> { return word.isBlank(); }); // single-expression lambda version words.removeIf(word -> word.isBlank()); // method reference version words.removeIf(String::isBlank);
Visit To learn more about removing null values from a list using different ways
and also visit Java Tutorials By Prakhar Yadav to learn more about java and get the solutions to all the problems you faced during solving java Questions and get tutorials.
And visit Understanding Python Dictionary Slicing – Detailed Tutorial with Examples and Problems to learn more about python and other programming languages.