How to remove all null elements from a Collection?
Posted by Mike Haller
on Sunday, February 4. 2007
at 00:24
in Java
A slightly annoying discussion was going on tonight on a Java IRC channel. It was all about how to remove null elements from an ArrayList.There have been a lot of questions by various people. Besided suggestions, technical questions, there have also been the
usual suspects like "Why on earth are you adding null elements anyway?".
But let's have a look at the result, which seems to be the easiest way:
list.removeAll(Collections.singleton(null));
If you don't know the Collections class, you might have been come up with something like this:
list.removeAll(Arrays.asList(new Object[]{null}));
Is there any other way to remove null references from collections? For example by using HashSets and only use remove(null). Or is it better to implement your own implementation of a Collection which does it itself?
What are the performance benefits of each variation? Could we use the Java High Performance Collections implementation Trove?
