Reputation: 4387
During a tutorial about the new JDK8 stream API I ran across the static .empty()
method of IntStream
, DoubleStream
and LongStream
.
So when does it make sense to use this methods?
Upvotes: 5
Views: 909
Reputation: 132390
(You had asked about the empty()
method on IntStream
, LongStream
, and DoubleStream
, but this method is also on the Stream
interface for reference types.)
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. In most cases you can't pass null
, you have to pass a stream of some sort. The way to get a stream that has no values is to use Stream.empty()
and friends.
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. The way this is done is to to have the flat-mapping operation return a stream of values. To have it return zero values, it returns an empty stream.
Upvotes: 4
Reputation: 100209
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:
public static IntStream ofOptional(OptionalInt optional) {
return optional.isPresent() ? IntStream.of(optional.get()) : IntStream.empty();
}
Actually such method is already added to JDK9.
Upvotes: 7
Reputation:
You can use to initialize an empty Stream, of any of the types mentioned by you. 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--
Upvotes: 3