Reputation: 37045
In C# I would use Enumerable.Empty()
, but how do I create an empty Stream
in Java?
Upvotes: 108
Views: 60060
Reputation: 14287
Stream<String> emptyStr = Stream.of();
emptyStr.count()
returns 0 (zero).
In addition:
IntStream
, IntStream.of()
works in
similar way (also the empty
method). IntStream.of(new int[]{})
also returns an empty stream.Arrays
class has stream creation methods which accept an
array of primitives or an object type. This can be used to create
an empty stream; e.g.,: System.out.println(Arrays.stream(new int[]{}).count());
prints zero.List
or Set
) with
zero elements can return an empty stream; for example: new ArrayList<Integer>().stream()
returns an empty stream of type Integer
.Upvotes: 13