-
Notifications
You must be signed in to change notification settings - Fork 5
Expand file tree
/
Copy pathExample4.java
More file actions
77 lines (47 loc) · 1.62 KB
/
Example4.java
File metadata and controls
77 lines (47 loc) · 1.62 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
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
package Java8;
import java.util.Arrays;
import java.util.List;
public class Example4 {
public static void main(String[] args) {
List<Integer> values = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);
// System.out.println(getUsingJava7(values));
System.out.println(getUsingJava8WithSepFunction(values));
}
// double the first even number in the list and it should be greater then 3
// o/p should be 4 * 2 = 8
private static Integer getUsingJava7(List<Integer> values) {
int result = 0;
for (Integer value : values) {
if (value > 3 && value % 2 == 0) {
result = value * 2;
break;
}
}
return result;
}
// lets do same thing using java8
// some times it throws null pointer exception
private static Integer getUsingJava8(List<Integer> values) {
// return values.stream().filter(e -> e > 3).filter(e -> e % 2 ==
// 0).map(e -> e * 2).findFirst();
return values.stream().filter(e -> e > 3).filter(e -> e % 2 == 0).map(e -> e * 2).findFirst().orElse(0);
}
// lets do some more generic way
// so create 3 different method 1 - greater than 3, 2 - %2 ==0 , 3 - *2
private static boolean isEven(int number) {
return number % 2 == 0;
}
private static boolean isGT3(int number) {
return number > 3;
}
private static int doubleIt(int number) {
return number*2;
}
private static Integer getUsingJava8WithSepFunction(List<Integer> values) {
return values.stream()
.filter(Example4::isGT3)
.filter(Example4::isEven)
.map(Example4::doubleIt)
.findFirst().orElse(0);
}
}