简体   繁体   English

IntStream.empty()方法的目的是什么?

[英]What's the purpose of the IntStream.empty() method?

During a tutorial about the new JDK8 stream API I ran across the static .empty() method of IntStream , DoubleStream and LongStream . 在关于新JDK8流API的教程中,我遇到了IntStreamDoubleStreamLongStream的静态.empty()方法。

So when does it make sense to use this methods? 那么什么时候使用这种方法有意义呢?

A good example is to create the IntStream from the OptionalInt : you want a singleton stream if the optional is present and an empty stream if the optional is absent: 一个很好的例子是从OptionalInt创建IntStream :如果存在可选项,则需要单例流;如果不存在可选项,则需要空流:

public static IntStream ofOptional(OptionalInt optional) {
    return optional.isPresent() ? IntStream.of(optional.get()) : IntStream.empty();
}

Actually such method is already added to JDK9. 实际上这种方法已经添加到JDK9中。

(You had asked about the empty() method on IntStream , LongStream , and DoubleStream , but this method is also on the Stream interface for reference types.) (您曾询问过IntStreamLongStreamDoubleStream上的empty()方法,但此方法也在Stream接口上用于引用类型。)

The general answer is that empty() is useful as a stream source for passing to an API that takes a stream -- either as an argument or as a return value -- and when you have no values to pass. 一般的答案是, empty()可用作传递给获取流的API的流源 - 无论是作为参数还是作为返回值 - 以及没有要传递的值。 In most cases you can't pass null , you have to pass a stream of some sort. 在大多数情况下,您不能传递null ,您必须传递某种类型的流。 The way to get a stream that has no values is to use Stream.empty() and friends. 获取没有值的流的方法是使用Stream.empty()和朋友。

Here's an example that repeats even numbers and drops odd numbers and collects them into a list: 这是一个重复偶数并丢弃奇数并将它们收集到列表中的示例:

    List<Integer> list = 
        IntStream.range(0, 10)
                 .flatMap(i -> (i & 1) == 0 ? IntStream.of(i, i) : IntStream.empty())
                 .boxed()
                 .collect(Collectors.toList());

The result is 结果是

[0, 0, 2, 2, 4, 4, 6, 6, 8, 8]

as one would expect. 正如人们所料。 The main point is that flatMap() passes in a single value and expects to receive an arbitrary number of values, including zero values. 重点是flatMap()传递一个值,并期望接收任意数量的值,包括零值。 The way this is done is to to have the flat-mapping operation return a stream of values. 这样做的方法是让flat-mapping操作返回一个值流。 To have it return zero values, it returns an empty stream. 要使其返回零值,它将返回一个空流。

You can use to initialize an empty Stream, of any of the types mentioned by you. 您可以使用初始化您提到的任何类型的空Stream。 I see it as a another way how to construct a new object. 我将其视为构建新对象的另一种方式。 Simple as that. 就那么简单。

https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#empty-- https://docs.oracle.com/javase/8/docs/api/java/util/stream/Stream.html#empty--

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM