How do I create an empty Stream in Java?

JavaJava StreamEnumerable

Java Problem Overview


In C# I would use Enumerable.Empty(), but how do I create an empty Stream in Java?

Java Solutions


Solution 1 - Java

As simple as this: Stream.empty()

Solution 2 - Java

Stream<String> emptyStr = Stream.of();

emptyStr.count() returns 0 (zero).


In addition:

  • For a primitive stream like IntStream, IntStream.of() works in similar way (also the empty method). IntStream.of(new int[]{}) also returns an empty stream.
  • The 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.
  • Any stream created from a collection (like a List or Set) with zero elements can return an empty stream; for example: new ArrayList<Integer>().stream() returns an empty stream of type Integer.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionsdgfsdhView Question on Stackoverflow
Solution 1 - JavaEugeneView Answer on Stackoverflow
Solution 2 - Javaprasad_View Answer on Stackoverflow