The current answers don't distinguish the mutable and immutable lists and I find a lot of ways missing. This becomes even more important with List.of(..)
introduced as of java-9, although one cannot pass a null
element to it. The removal is relevant anyway (ex. removing a certain non-null element).
Immutable List
An example of a immutable list is Arrays.asList(..)
(yet the elements can still be replaced, but not added/removed) or already mentioned List.of(..)
. These are considered as "immutable wrappers" as long as one cannot add/remove an element using the List
methods.
List<String> immutableList = Arrays.asList("one", null, "two");
java-stream as of java-8 using the Stream#filter(Predicate)
method:
List<String> newList = immutableList.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());
For-each loop either with indices or the enhanced one is suitable (not only) for Java versions java-7 and lower.
// note we need to create a mutable List to add the non-null elements
List<String> newList = new ArrayList<>();
for (String str: immutableList) {
if (str != null) {
newList.add(str);
}
}
Mutable List
An example of a mutable list is a new instance of the List
interface such as new ArrayList<>()
or new LinkedList<>()
. They are mutable, therefore adding the elements using List#add
or List#addAll
is possible and a common way to do so.
List<String> mutableList = new ArrayList<>(Arrays.asList("one", null, "two"));
Here are listed ways to remove all the null
elements from such List
. Note it modifies the list.
List#removeIf(Predicate)
as of java-8
mutableList.removeIf(Objects::isNull);
Iterator
is a recommended way to remove elements from a List
and is suitable (not only) for Java versions java-7 and lower
Iterator<String> iterator = mutableList.iterator();
while (iterator.hasNext()) {
if (iterator.next() == null) {
iterator.remove();
}
}
All the ways mentioned in the Immutable List section which always results in a new List
.