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

How to 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.


As of 2015, this is the best way (Java 8):

tourists.removeIf(Objects::isNull);

Note: This code will throw java.lang.UnsupportedOperationException for fixed-size lists (such as created with Arrays.asList), including immutable lists.


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

It will Throws UnsupportedException if you use it on Arrays.asList because it give you Immutable copy so it can not be modified. See below the code. It creates Mutable copy and will not throw any exception.

public static String[] clean(final String[] v) {    List<String> list = new ArrayList<String>(Arrays.asList(v));    list.removeAll(Collections.singleton(null));    return list.toArray(new String[list.size()]);}