Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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?

like image 979
Ezequiel Avatar asked Dec 03 '14 09:12

Ezequiel


People also ask

Is an empty ArrayList null?

No. An ArrayList can be empty (or with nulls as items) an not be null. It would be considered empty.

Is it better to return null or empty list?

It is better to return empty collections rather than null when writing methods. The reason being that any code calling your method then doesn't need to explicitly handle a special null case. Returning an empty collection makes the null check redundant and results in much cleaner method calling code.

How do I return an empty list?

emptyList() returns an immutable list, i.e., a list to which you cannot add elements if you want to perform any operation on your list, then create new instance of list and return it. if (isValidLang(lang)) { query.

Can I set an ArrayList to null?

null is a perfectly valid element of an ArrayList. The difference is in the List size, not its capacity. When instantiating a new ArrayList<>(5) , the initial capacity is set to 5, but the size remains 0, because we haven't added any elements.


3 Answers

You can use Java 8 Optional:

String[] arr = null;
List<String> list = Arrays.asList(Optional.ofNullable(arr).orElse(new String[0]));
like image 192
Eran Avatar answered Oct 12 '22 00:10

Eran


You can use Java 8 Optionaland Stream

Optional.ofNullable(possibleNullArray)
        .map(Arrays::stream)
        .orElseGet(Stream::empty)
        .collect(Collectors.toList())
like image 22
Nicolas Henneaux Avatar answered Oct 12 '22 02:10

Nicolas Henneaux


I'm not aware of any util method in Apache Commons / Guava that would create an empty List instance out of null.

The best thing you can probably do is to initialize the possibly null array beforehand, e.g. with ArrayUtils.nullToEmpty(). Get rid of the null as soon as you can.

SomeObject[] array = ArrayUtils.nullToEmpty(possiblyNullArray);
like image 18
Petr Janeček Avatar answered Oct 12 '22 02:10

Petr Janeček