views:

1071

answers:

1

Hi,

Suppose 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);

Now, list only contains "s1", "s2", "s4", "s4". Non-null references.

What should i use in order to fulfill this requirement ?

regards,

+9  A: 
list.removeAll(Collections.singletonList(null));
Michael Borgwardt
Cool, I didn't know about singletonList(). That's more elegant than my three-liner.
Rob Hruska
The Collections and Array classes are true treasure troves - and singletonList() as well as emptyList() are the main reasons why using ArraList or Vector as method parameter type anywhere should be punished with at least 20 lashes.
Michael Borgwardt
It could also have been `list.removeAll(Arrays.asList(null))`, but `singletonList` is slightly quicker.
Michael Myers
And it's downwards compatible to pre-varargs Java versions.
Michael Borgwardt
Very good. Congratulations.
Arthur Ronald F D Garcia