Skip to content

Commit 9d6a52f

Browse files
committed
Added of(), iterate() and generate() Stream Operations
1 parent a09ac79 commit 9d6a52f

File tree

2 files changed

+42
-1
lines changed

2 files changed

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

README.md

Lines changed: 3 additions & 1 deletion
Original file line numberDiff line numberDiff line change
@@ -36,12 +36,14 @@ This repository contains the basic &amp; advance level examples related to Java
3636
* [skip() and limit()](Modern-Java-Examples/src/com/learn/streams/StreamsLimitSkipExample.java)
3737
* [allMatch(), anyMatch() and noneMatch()](Modern-Java-Examples/src/com/learn/streams/StreamsMatchExample.java)
3838
* [findFirst() and findAny()](Modern-Java-Examples/src/com/learn/streams/StreamsFindExample.java)
39+
* [of(), iterate() and generate()](Modern-Java-Examples/src/com/learn/streams/StreamOfGenerateIterateExample.java)
40+
3941

4042
<hr />
4143

4244
## Contributing
4345

44-
This repository is a personal project and accept pull requests to maintain consistency in Java Coding Style. However, feel free to fork the repository and modify it as needed.
46+
This repository is a personal project, but we welcome pull requests to keep the Java coding style up to date with new concepts. Additionally, feel free to fork the repository and modify it as you see fit.
4547

4648

4749

0 commit comments

Comments
 (0)