How to Efficiently Remove All Null Elements from a Arraylist or String Array

How to efficiently remove all null elements from a ArrayList or String Array?

Try:

tourists.removeAll(Collections.singleton(null));

Read the Java API. The code will throw java.lang.UnsupportedOperationException for immutable lists (such as created with Arrays.asList); see this answer for more details.

Remove null elements from list

This should work:

list.removeAll(Collections.singleton(null));  

Java - Remove null from list of Objects

Mutable list

You can use List::removeIf with a predicate detecting null items.

List<Object[]> mutableList = new ArrayList<>(Arrays.asList(
new Object[] {},
null,
new Object[] {}));

mutableList.removeIf(Objects::isNull);

Immutable list

In this case you have to use Stream API or a for-loop to find non-null elements and add them to a new list.

List<Object[]> immutableList = Arrays.asList(
new Object[] {},
null,
new Object[] {});

List<Object[]> newList = immutableList.stream()
.filter(Objects::nonNull)
.collect(Collectors.toList());

Remove Null Value from String array in java

If you want to avoid fencepost errors and avoid moving and deleting items in an array, here is a somewhat verbose solution that uses List:

import java.util.ArrayList;
import java.util.List;

public class RemoveNullValue {
public static void main( String args[] ) {
String[] firstArray = {"test1", "", "test2", "test4", "", null};

List<String> list = new ArrayList<String>();

for(String s : firstArray) {
if(s != null && s.length() > 0) {
list.add(s);
}
}

firstArray = list.toArray(new String[list.size()]);
}
}

Added null to show the difference between an empty String instance ("") and null.

Since this answer is around 4.5 years old, I'm adding a Java 8 example:

import java.util.Arrays;
import java.util.stream.Collectors;

public class RemoveNullValue {
public static void main( String args[] ) {
String[] firstArray = {"test1", "", "test2", "test4", "", null};

firstArray = Arrays.stream(firstArray)
.filter(s -> (s != null && s.length() > 0))
.toArray(String[]::new);

}
}


Related Topics



Leave a reply



Submit