Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Helper to remove null references in a Java List?

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?

like image 433
Arthur Ronald Avatar asked Aug 06 '09 15:08

Arthur Ronald


People also ask

Can we remove null from list?

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.

How do you get rid of null in Java?

string. replace("null", ""); You can also replace all the instances of 'null' with empty String using replaceAll.


2 Answers

list.removeAll(Collections.singleton(null)); 
like image 190
Michael Borgwardt Avatar answered Oct 12 '22 23:10

Michael Borgwardt


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.

like image 27
Jeffrey Bosboom Avatar answered Oct 13 '22 00:10

Jeffrey Bosboom