Java – Null array to empty list


Arrays.asList(E[] e) returns a view of the array as a List, but when array is null it throws a NullPointerException.

Arrays.asList(null); //NullPointerException.

Actually I'm doing

 List list = possibleNullArray != null ? Arrays.asList(possibleNullArray) : Collections.EMPTY_LIST;

However, creating a Utility class in my project only for this purpose is a thing that I prefer not to do. Is there some utility Class, or library like Apache Commons or Guava to convert null arrays to empty List? (i.e. a null-safe converter between arrays and Collections).

How would you solve this problem?

Best Solution

You can use Java 8 Optional:

String[] arr = null;
List<String> list = Arrays.asList(Optional.ofNullable(arr).orElse(new String[0]));