Java 空数组到空列表

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/27268307/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-11 04:04:22  来源:igfitidea点击:

Null array to empty list

javaarrayscollections

提问by Ezequiel

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

Arrays.asList(E[] e)将数组的视图作为 a 返回List,但是当数组为 null 时,它会抛出 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).

但是,仅出于此目的在我的项目中创建 Utility 类是我不愿意做的事情。是否有一些实用程序类或像 Apache Commons 或 Guava 这样的库可以将空数组转换为空数组List?(即数组和集合之间的空安全转换器)。

How would you solve this problem?

你会如何解决这个问题?

采纳答案by Petr Jane?ek

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

我不知道 Apache Commons / Guava 中的任何 util 方法会List从 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.

您可能做的最好的事情是事先初始化可能为空的数组,例如使用ArrayUtils.nullToEmpty(). 尽快摆脱空值。

SomeObject[] array = ArrayUtils.nullToEmpty(possiblyNullArray);

回答by Eran

You can use Java 8 Optional:

您可以使用 Java 8 Optional

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

回答by Nicolas Henneaux

You can use Java 8 Optionaland Stream

您可以使用 Java 8OptionalStream

Optional.ofNullable(possibleNullArray)
        .map(Arrays::stream)
        .orElseGet(Stream::empty)
        .collect(Collectors.toList())