-
Notifications
You must be signed in to change notification settings - Fork 61
/
Copy pathSupplierFunctionalInterfaceTest.java
86 lines (64 loc) · 2.02 KB
/
SupplierFunctionalInterfaceTest.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
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
package suppliers;
import static org.hamcrest.MatcherAssert.assertThat;
import static org.hamcrest.Matchers.equalTo;
import java.util.ArrayList;
import java.util.List;
import java.util.Random;
import java.util.function.Supplier;
import java.util.stream.Collectors;
import java.util.stream.Stream;
import org.junit.Test;
public class SupplierFunctionalInterfaceTest {
@Test
public void shouldGetTheTextByUsingSupplierWithoutLambdaExpression() throws Exception {
Supplier<String> supplier = new Supplier<String>() {
@Override
public String get() {
return "Java 8 - Supplier by Craft Coder";
}
};
String guide = supplier.get();
assertThat(guide, equalTo("Java 8 - Supplier by Craft Coder"));
}
@Test
public void shouldGetTheTextByUsingSupplierWithLambdaExpression() throws Exception {
Supplier<String> supplier = () -> "Java 8 - Supplier by Craft Coder";
String guide = supplier.get();
assertThat(guide, equalTo("Java 8 - Supplier by Craft Coder"));
}
@Test
public void shouldGetAListOfRandomNumbersByUsingLoops() throws Exception {
List<Integer> randomNumbers = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Integer number = RandomNumbers.getNext();
randomNumbers.add(number);
}
System.out.println(randomNumbers);
}
@Test
public void shouldGetAListOfRandomNumbersGreaterThan5ByUsingLoops() throws Exception {
List<Integer> randomNumbers = new ArrayList<>();
for (int i = 0; i < 10; i++) {
Integer number = RandomNumbers.getNext();
if (number > 5) {
randomNumbers.add(number);
}
}
System.out.println(randomNumbers);
}
@Test
public void shouldGetAListOfRandomNumbersByUsingSupplier() throws Exception {
Supplier<Integer> supplier = () -> RandomNumbers.getNext();
List<Integer> randomNumbers = Stream
.generate(supplier)
.filter(number -> number > 5)
.limit(10)
.collect(Collectors.toList());
System.out.println(randomNumbers);
}
}
class RandomNumbers {
public static Integer getNext() {
return new Random().nextInt(10);
}
}