Java streams can be created in many ways based upon your use case.
Let us explore different ways of creating streams.
Collections
Streams can be created from collections like List, Set and Map.
In the below example we can see how streams can be created for a List.
We can create streams by calling stream()
on a collection.
From List
|
|
From Set
|
|
From Map
For map we need call stream()
method on entrySet()
|
|
Arrays
We can also create stream from Arrays as shown in below example.
We pass array as argument to Arrays.stream()
method.
|
|
Stream Builder
We can create stream step by step just like in builder pattern.
Stream builder is created by using Stream.builder()
and we can add elements to it by using add()
method as shown
in below example.
|
|
Primitive streams
We can create primitive streams like int, long and double by using inbuilt functionality.
We can create stream of ints using IntStream
class as shown in below code
|
|
Similarly we can primitive stream for double and long.
|
|
We can create range of primitive values by using IntStream.range(1,10)
.
|
|
Stream.generate
Returns an infinite sequential unordered stream where each element is generated by the provided Supplier. This is suitable for generating constant streams, streams of random elements, etc.
In the below example we are creating 10 id’s based on the logic given in the Supplier
.
|
|
Stream.iterate
Returns an infinite sequential ordered Stream produced by iterative application of a function f to an initial element seed.
In the below example seed is 10 and want 5 even numbers.
|
|
File Stream
Stream of file can be generated using lines()
method.
This stream can be used to manipulate the content of the file accordingly by using stream api.
In the below example we read from ’names.txt’ file and simply add convert all content to uppercase.
|
|
Empty Stream
Empty stream is created by using Stream.empty()
as shown in below code.
Since stream is empty, no of elements in the stream will be zero as shown in below code.
|
|
Thus we have learnt how to create stream using different ways.
Hope this was helpful to you!