Reputation: 3592
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?
Upvotes: 34
Views: 49274
Reputation: 12215
You can use Java 8 Optional
and Stream
Optional.ofNullable(possibleNullArray)
.map(Arrays::stream)
.orElseGet(Stream::empty)
.collect(Collectors.toList())
Upvotes: 21
Reputation: 38424
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);
Upvotes: 21
Reputation: 393831
You can use Java 8 Optional
:
String[] arr = null;
List<String> list = Arrays.asList(Optional.ofNullable(arr).orElse(new String[0]));
Upvotes: 46