In C# I would use Enumerable.Empty()
, but how do I create an empty Stream
in Java?
Asked
Active
Viewed 5.3k times
102
-
6StackOverflow is more google-able than the documentation. – sdgfsdh Feb 28 '17 at 12:21
-
3You 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
-
8When 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 Answers
186
As simple as this: Stream.empty()

Murat Karagöz
- 35,401
- 16
- 78
- 107

Eugene
- 117,005
- 15
- 201
- 306
-
17
-
-
Because if you don't, compiler assumes the type is `Stream extends Object>`, and why won't it? – Mugen Mar 01 '20 at 15:23
-
1@Mugen you need to provide an example or ask a question, this is not how type inference should work. – Eugene Mar 01 '20 at 15:25
-
I provided a tip, if you think I'm wrong I'll delete it as this is your answer and I don't intend to start a new discussion. – Mugen Mar 01 '20 at 15:28
-
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 theempty
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
orSet
) with zero elements can return an empty stream; for example:new ArrayList<Integer>().stream()
returns an empty stream of typeInteger
.

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
-
10In 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