gpt4 book ai didi

java - Java 8 中的空安全集合作为流

转载 作者:IT老高 更新时间:2023-10-28 20:43:17 28 4
gpt4 key购买 nike

我正在寻找可以制作集合流的方法,但它是 null 安全的。如果collection 为null,则返回空流。像这样:

Utils.nullSafeStream(collection).filter(...);

我已经创建了自己的方法:

public static <T> Stream<T> nullSafeStream(Collection<T> collection) {
if (collection == null) {
return Stream.empty();
}
return collection.stream();
}

但我很好奇,标准JDK中是否有类似的东西?

最佳答案

你可以使用 可选 :

Optional.ofNullable(collection).orElse(Collections.emptySet()).stream()...

我任意选择了Collections.emptySet() 作为默认值,以防collection 为空。如果 collection 为空,这将导致 stream() 方法调用产生一个空的 Stream

例子:

Collection<Integer> collection = Arrays.asList (1,2,3);
System.out.println (Optional.ofNullable(collection).orElse(Collections.emptySet()).stream().count ());
collection = null;
System.out.println (Optional.ofNullable(collection).orElse(Collections.emptySet()).stream().count ());

输出:

3
0

或者,按照 marstran 的建议,您可以使用:

Optional.ofNullable(collection).map(Collection::stream).orElse(Stream.empty ())...

关于java - Java 8 中的空安全集合作为流,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/41590134/

28 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com