Skip to content

Commit 8378d6f

Browse files
committed
lambda example
1 parent 72803f8 commit 8378d6f

1 file changed

Lines changed: 20 additions & 12 deletions

File tree

example-code/LambdaExample.java

Lines changed: 20 additions & 12 deletions
Original file line numberDiff line numberDiff line change
@@ -1,14 +1,22 @@
1+
import java.util.function.*;
2+
import java.util.ArrayList;
3+
14
public class LambdaExample {
2-
public static void main(String[] args) {
3-
java.util.function.Function<Integer, Integer> square =
4-
x -> {
5-
int result = 0;
6-
for (int i=0;
7-
i<x;
8-
i++)
9-
result++;
10-
return result;
11-
};
12-
System.out.println(square.apply(5));
13-
}
5+
6+
static Function<Integer, Integer> inc(int x) {
7+
return y -> x+y;
8+
}
9+
10+
static Function<Integer, Integer> mul(int x) {
11+
return y -> x*y;
12+
}
13+
14+
public static void main(String[] args) {
15+
// bad style, generic erasure to get array
16+
Function[] fs = {inc(5), inc(10), mul(7), mul(2)};
17+
18+
for (Function f : fs)
19+
System.out.println(
20+
((Function<Integer, Integer>)f).apply(100));
21+
}
1422
}

0 commit comments

Comments
 (0)