102

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

azurefrog
  • 10,785
  • 7
  • 42
  • 56
sdgfsdh
  • 33,689
  • 26
  • 132
  • 245
  • 6
    StackOverflow is more google-able than the documentation. – sdgfsdh Feb 28 '17 at 12:21
  • 3
    You don’t need google at all. There is exactly one address to bookmark once when starting to develop Java software, https://docs.oracle.com/javase/8/docs/api which is the official API documentation containing each package, class and member in a structure not requiring a search engine to find them. – Holger Feb 28 '17 at 12:57
  • 8
    When you already know that it exists, then yes. But Java abounds with library methods that you might hope exist, but turn out not to (or not where you thought, or with the name you thought), and you could spend quite a bit of your life looking for them if you always made the API doc your first port of call. – Andrew Spencer Feb 22 '18 at 10:16

2 Answers2

186

As simple as this: Stream.empty()

Murat Karagöz
  • 35,401
  • 16
  • 78
  • 107
Eugene
  • 117,005
  • 15
  • 201
  • 306
13
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.
prasad_
  • 12,755
  • 2
  • 24
  • 36
  • This is shorter than the accepted answer; it makes you wonder why `Stream.empty()` was created. – sdgfsdh Apr 18 '18 at 12:29
  • 10
    In oppposite to `Stream.empty()`, it creates empty array internally, performs null check on it etc. You can look it up in implementation. – Marcin Majkowski Apr 26 '18 at 08:50