如何最好地从可为空的对象创建 Java 8 流?

2022-01-22 00:00:00 java-8 java java-stream

在获取流之前进行空检查的最佳/惯用方法是什么?

What is the best/idiomatic way of doing a null check before getting a stream?

我有一个接收可能为空的 List 的方法.所以我不能只对传入的值调用 .stream() .如果值为空,是否有一些静态助手会给我一个空流?

I have method that is receiving a List that might be null. So I can't just call .stream() on the passed in value. Is there some static helper in that would give me an empty stream if a value is null?

推荐答案

我同意 Stuart Marks 的观点 <代码>列表 == 空?Stream.empty() : list.stream() 是执行此操作的正确方法(请参阅他的答案),或者至少是在 Java 9 之前执行此操作的正确方法(请参阅下面的编辑),但我将保留此答案以演示可选 API 的用法.

I agree with Stuart Marks that list == null ? Stream.empty() : list.stream() is the right way to do this (see his answer), or at least the right way to do this pre-Java 9 (see edit below), but I'll leave this answer up to demonstrate usage of the Optional API.

<T> Stream<T> getStream(List<T> list) {
    return Optional.ofNullable(list).map(List::stream).orElseGet(Stream::empty);
}

<小时>

Java 9 添加了静态工厂方法 Stream.<T>ofNullable(T),返回给定 null 的空流参数,否则以参数为唯一元素的流.如果参数是一个集合,那么我们可以 flatMap 把它变成一个流.


Java 9 added the static factory method Stream.<T>ofNullable(T), which returns the empty stream given a null argument, otherwise a stream with the argument as its only element. If the argument is a collection, we can then flatMap to turn it into a stream.

<T> Stream<T> fromNullableCollection(Collection<? extends T> collection) {
    return Stream.ofNullable(collection).flatMap(Collection::stream);
}

这不会滥用 Stuart Marks 所讨论的 Optional API,并且与三元运算符解决方案相比,没有机会出现空指针异常(例如,如果您没有注意并搞砸了操作数).由于 flatMap 的签名,它还可以使用上限通配符而不需要 SuppressWarnings("unchecked"),因此您可以获得 Stream<T> 来自 T 的任何子类型的元素集合.

This doesn't misuse the Optional API as discussed by Stuart Marks, and in contrast to the ternary operator solution, there's no opportunity for a null pointer exception (like if you weren't paying attention and screwed up the order of the operands). It also works with an upper-bounded wildcard without needing SuppressWarnings("unchecked") thanks to the signature of flatMap, so you can get a Stream<T> from a collection of elements of any subtype of T.

相关文章