Java函数式接口

The world rushes on over the strings of the lingering heart making the music of sadness.

世界在踌躇之心的琴弦上跑过去,奏出忧郁的乐声。

函数式接口

函数式接口(Functional Interface)就是一个有且仅有一个抽象方法,但是可以有多个非抽象方法的接口。

函数式接口可以被隐式转换为Java-Lambda表达式

Lambda 表达式和方法引用(实际上也可认为是Lambda表达式)上。

如定义了一个函数式接口如下:

1
2
3
4
5
@FunctionalInterface
interface GreetingService
{
void sayMessage(String message);
}

那么就可以使用Java-Lambda表达式来表示该接口的一个实现(注:JAVA 8 之前一般是用匿名类实现的):

1
GreetingService greetService1 = message -> System.out.println("Hello " + message);

函数式接口实例

Predicate 接口是一个函数式接口,它接受一个输入参数 T,返回一个布尔值结果。

该接口包含多种默认方法来将Predicate组合成其他复杂的逻辑(比如:与,或,非)。

该接口用于测试对象是 true 或 false。

我们可以通过以下实例(Java8Tester.java)来了解函数式接口 Predicate 的使用:

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
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

public class Java8Tester {
public static void main(String args[]){
List<Integer> list = Arrays.asList(1, 2, 3, 4, 5, 6, 7, 8, 9);

// Predicate<Integer> predicate = n -> true
// n 是一个参数传递到 Predicate 接口的 test 方法
// n 如果存在则 test 方法返回 true

System.out.println("输出所有数据:");

// 传递参数 n
eval(list, n->true);

// Predicate<Integer> predicate1 = n -> n%2 == 0
// n 是一个参数传递到 Predicate 接口的 test 方法
// 如果 n%2 为 0 test 方法返回 true

System.out.println("输出所有偶数:");
eval(list, n-> n%2 == 0 );

// Predicate<Integer> predicate2 = n -> n > 3
// n 是一个参数传递到 Predicate 接口的 test 方法
// 如果 n 大于 3 test 方法返回 true

System.out.println("输出大于 3 的所有数字:");
eval(list, n-> n > 3 );
}

public static void eval(List<Integer> list, Predicate<Integer> predicate) {
for(Integer n: list) {

if(predicate.test(n)) {
System.out.println(n + " ");
}
}
}
}

/*
$ javac Java8Tester.java
$ java Java8Tester
输出所有数据:
1
2
3
4
5
6
7
8
9
输出所有偶数:
2
4
6
8
输出大于 3 的所有数字:
4
5
6
7
8
9
*/
查看评论