-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathLambdaTest.java
52 lines (40 loc) · 1.28 KB
/
LambdaTest.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
package com.newfeatures;
import java.util.Objects;
@FunctionalInterface
interface Consumer<T> {
void accept(T t);
// andThen先执行调用者再执行参数,compose则相反
default Consumer<T> andThen(Consumer<? super T> after) {
Objects.requireNonNull(after); // 空对象报异常,否则返回自身
return (T t) -> {
accept(t);
after.accept(t);
};
}
}
public class LambdaTest {
public static void ConsumerApple(Apple[] apps, Consumer<Apple> c) {
for (Apple app : apps) {
c.accept(app);
}
}
public static void main(String[] args) {
Apple app1 = new Apple("red", 3.0);
Apple app2 = new Apple("blue", 4.0);
Apple app3 = new Apple("green", 5.0);
Apple[] apps = {app1, app2, app3};
// lambda形式
System.out.println("lambda实现函数式接口");
ConsumerApple(apps, (c) -> {
System.out.println(c.toString());
});
// 匿名内部类
System.out.println("匿名内部类实现函数式接口");
ConsumerApple(apps, new Consumer<Apple>() {
@Override
public void accept(Apple apple) {
System.out.println(apple.toString());
}
});
}
}