How to check if a Java 8 Stream is empty?
This may be sufficient in many cases
stream.findAny().isPresent()
The other answers and comments are correct in that to examine the contents of a stream, one must add a terminal operation, thereby "consuming" the stream. However, one can do this and turn the result back into a stream, without buffering up the entire contents of the stream. Here are a couple examples:
static <T> Stream<T> throwIfEmpty(Stream<T> stream) {
Iterator<T> iterator = stream.iterator();
if (iterator.hasNext()) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
} else {
throw new NoSuchElementException("empty stream");
}
}
static <T> Stream<T> defaultIfEmpty(Stream<T> stream, Supplier<T> supplier) {
Iterator<T> iterator = stream.iterator();
if (iterator.hasNext()) {
return StreamSupport.stream(Spliterators.spliteratorUnknownSize(iterator, 0), false);
} else {
return Stream.of(supplier.get());
}
}
Basically turn the stream into an Iterator
in order to call hasNext()
on it, and if true, turn the Iterator
back into a Stream
. This is inefficient in that all subsequent operations on the stream will go through the Iterator's hasNext()
and next()
methods, which also implies that the stream is effectively processed sequentially (even if it's later turned parallel). However, this does allow you to test the stream without buffering up all of its elements.
There is probably a way to do this using a Spliterator
instead of an Iterator
. This potentially allows the returned stream to have the same characteristics as the input stream, including running in parallel.