Given the following List:
List<String> list = new ArrayList<String>(); list.add("s1"); list.add("s2"); list.add(null); list.add("s3"); list.add(null); list.add("s4");
I need a helper class that removes null references. Something like:
SomeHelper.removeNullReference(list);
such that the list only contains "s1", "s2", "s4", "s4" (non-null references).
What should I use to fulfill this requirement?
Using List. To remove all null occurrences from the list, we can continuously call remove(null) until all null values are removed. Please note that the list will remain unchanged if it does not contain any null value.
string. replace("null", ""); You can also replace all the instances of 'null' with empty String using replaceAll.
list.removeAll(Collections.singleton(null));
Java 8 added Collection.removeIf(Predicate)
that removes all elements matching the predicate, so you can remove all occurrences of null
from a list (or any collection) with
list.removeIf(Objects::isNull);
using java.util.Objects.isNull
as a Predicate
.
You can also use .removeIf(x -> x == null)
if you prefer; the difference is very minor.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With