Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I create an empty Stream in Java?

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

like image 713
sdgfsdh Avatar asked Feb 15 '17 14:02

sdgfsdh


People also ask

What happens if you stream an empty list Java?

You will get a empty collection because of the origin input is empty or due to the filter operation.

How many ways we can create stream in Java?

Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.


2 Answers

As simple as this: Stream.empty()

like image 141
Eugene Avatar answered Nov 16 '22 00:11

Eugene


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.
like image 20
prasad_ Avatar answered Nov 16 '22 00:11

prasad_