Repository navigation
Expand file tree
/
Copy pathStreamGenerate.java
More file actions
44 lines (33 loc) · 1.53 KB
/
Copy pathStreamGenerate.java
File metadata and controls
44 lines (33 loc) · 1.53 KB
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
40
41
42
43
44
package com.uk.streamapi.stream;
import java.util.function.Consumer;
import java.util.function.Supplier;
import java.util.stream.Stream;
public class StreamGenerate {
static void main() {
// @FunctionalInterface
// public interface Supplier<T> { T get(); } is a functional interface with one abstract method which is get() which returns the T type of results
Supplier<String> supplierAnonymousClass = new Supplier<String>() {
@Override
public String get() {
return "hello stream!!";
}
};
Supplier<String> supplierLambda = () -> "hello stream!!";
// Both supplierAnonymousClass and supplierLambda exhibit same behaviour
// Stream.generate(Supplier s) static method returns an infinite sequential unordered stream where each element is generated by the supplier
// In this case generate() is working as a DataSource
Stream<String> streamOfStrings = Stream.generate(supplierLambda);
// @FunctionalInterface
// public interface Consumer<T> { void accept(T t); } is a functional interface with one abstract method which accept(T t) and a default method addThen
Consumer<String> consumerAnonymousClass = new Consumer<String>() {
@Override
public void accept(String s) {
System.out.println(s);
}
};
Consumer<String> cosumerLambda = (s) -> System.out.println(s);
// Both consumerAnonymousClass and cosumerLambda exhibit same behaviour
// forEach(consumer) method is a terminal operation which consumes the stream and calls the accept() method of consumer
streamOfStrings.limit(5).forEach(cosumerLambda);
}
}