What is the purpose of the IntStream.empty () method?

During the tutorial on the new JDK8 thread API, I came across a static .empty()method IntStream, DoubleStreamand LongStream.

So, when does it make sense to use these methods?

+4
source share
3 answers

You can use any of the types you specify to initialize an empty stream. I see this as another way to create a new object. Just like that.

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

+3
source

A good example is creating IntStreamfrom OptionalInt: you need a singleton stream if optional is present, and an empty stream if optional is missing:

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

JDK9.

+7

( empty() IntStream, LongStream DoubleStream, Stream .)

: empty() API, - , - . null, - . , , Stream.empty() .

, :

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

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

as expected. The main thing is that flatMap()it goes into one value and expects to get an arbitrary number of values, including zero values. The way this is done is for the flat matching operation to return a stream of values. So that it returns null values, it returns an empty stream.

+4
source

All Articles