-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathStreamOfGenerateIterateExample.java
39 lines (32 loc) · 1.13 KB
/
StreamOfGenerateIterateExample.java
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
package com.learn.streams;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class StreamOfGenerateIterateExample {
public static void main(String[] args) {
/**
* Create Stream using of() method.
*/
Stream<String> stringStream = Stream.of("John", "Doe", "Mark", "Vince");
stringStream.forEach(System.out::println);
/**
* It will iterate infinite times.
* 1: initial Value
*/
Stream.iterate(1, x -> x * 2)
.forEach(System.out::println);
// but we can use limit to limit the no of values it can pick from stream
Stream.iterate(1, x -> x * 2)
.limit(10)
.forEach(System.out::println);
Supplier<Integer> integerSupplier = new Random()::nextInt; // gives random values
/**
* <p>
* generate() also generates infinite streams, but we can limit using limit() operation.
* </p>
*/
Stream.generate(integerSupplier)
.limit(5)
.forEach(System.out::println);
}
}