Different Ways of Creating Java Streams

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

1
2
3
4
5
6
7
8
9
List<Integer> nums = Arrays.asList(10, 20, 30, 40, 50);
nums.stream().forEach(System.out::println);

Output:
10
20
30
40
50

From Set

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
Set<String> names= new HashSet<>();
names.add("Jim");
names.add("Tim");
names.add("Mary");
names.stream().forEach(System.out::println);

Output:
Tim
Jim
Mary

From Map

For map we need call stream() method on entrySet()

1
2
3
4
5
6
Map<String,String> data = new HashMap<>();
data.put("1","Java");
data.put("2","Python");
data.put("3","SQL");

System.out.println(data.entrySet().stream().count()); // 3

Arrays

We can also create stream from Arrays as shown in below example.

We pass array as argument to Arrays.stream() method.

1
2
3
4
5
int[] nums = new int[] {10,20,30};

IntStream data = Arrays.stream(nums);

data.forEach(System.out::println); //10 20 30

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.

1
2
3
4
5
Stream<String> namesBuilder = Stream.<String>builder()
                                .add("Tim")
                                .add("Zack")
                                .add("Mary").build();
System.out.println(namesBuilder.count());  // 3

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

1
2
IntStream intStream = IntStream.of(10, 20, 30);
System.out.println(intStream.count()); //3 

Similarly we can primitive stream for double and long.

1
2
3
4
5
DoubleStream doubleStream = DoubleStream.of(10.0, 20.0, 30.0);
System.out.println(doubleStream.count());  // 3

LongStream longStream = LongStream.of(10l, 20l, 30l);
System.out.println(longStream.count()); // 3

We can create range of primitive values by using IntStream.range(1,10).

1
2
IntStream rangeInStream = IntStream.range(1,10);
rangeInStream.forEach(System.out::println);

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
AtomicInteger integer= new AtomicInteger();
Stream<String> generate = Stream.generate(() -> {
            return "Id" + integer.getAndIncrement();
        }).limit(10);

generate.forEach(System.out::println); 

Output:
Id0
Id1
Id2
Id3
Id4
Id5
Id6
Id7
Id8
Id9

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.

1
2
Stream<Integer> iterateStream = Stream.iterate(10, x -> x + 2).limit(5);
iterateStream.forEach(System.out::println); // 10 12 14 16 18

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.

 1
 2
 3
 4
 5
 6
 7
 8
 9
10
11
12
13
14
15
16
17
18
Path path = Paths.get("C:\\dev\\names.txt");

try {
    Stream<String> lines = Files.lines(path);
    lines.map(String::toUpperCase).forEach(System.out::println);
} catch (IOException e) {
    throw new RuntimeException(e);
}


Output:
---------
JIM
TIM
JANE
MARY
ROCKY
ZACK

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.

1
2
Stream<Object> emptyStream = Stream.empty();
System.out.println(emptyStream.count()); // 0

Thus we have learnt how to create stream using different ways.

Hope this was helpful to you!