Functional Programming With Java 简明教程
Functional Programming - Functional Interfaces
函数式接口具有单一功能可表现。例如,带有单个方法“compareTo”的 Comparable 接口用于比较目的。Java 8 已经定义了很多函数式接口,以便在 lambda 表达式中广泛使用。以下是 java.util.Function 包中定义的函数式接口列表。
Functional interfaces have a single functionality to exhibit. For example, a Comparable interface with a single method 'compareTo' is used for comparison purpose. Java 8 has defined a lot of functional interfaces to be used extensively in lambda expressions. Following is the list of functional interfaces defined in java.util.Function package.
Functional Interface Example
Predicate <T> 接口是一个函数式接口,具有一个方法 test(Object),用于返回一个布尔值。此接口表示将对某个对象进行真或假测试。
Predicate <T> interface is a functional interface with a method test(Object) to return a Boolean value. This interface signifies that an object is tested to be true or false.
在任意编辑器中创建以下 Java 程序,例如,在 C:\> JAVA 中创建。
Create the following Java program using any editor of your choice in, say, C:\> JAVA.
Java8Tester.java
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 is passed as parameter to test method of Predicate interface
// test method will always return true no matter what value n has.
System.out.println("Print all numbers:");
//pass n as parameter
eval(list, n->true);
// Predicate<Integer> predicate1 = n -> n%2 == 0
// n is passed as parameter to test method of Predicate interface
// test method will return true if n%2 comes to be zero
System.out.println("Print even numbers:");
eval(list, n-> n%2 == 0 );
// Predicate<Integer> predicate2 = n -> n > 3
// n is passed as parameter to test method of Predicate interface
// test method will return true if n is greater than 3.
System.out.println("Print numbers greater than 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 + " ");
}
}
}
}
这里我们传递了 Predicate 接口,它采用一个输入并返回布尔值。
Here we’ve passed Predicate interface, which takes a single input and returns Boolean.
Verify the Result
按照如下方式使用 javac 编译器编译类 −
Compile the class using javac compiler as follows −
C:\JAVA>javac Java8Tester.java
现在按照如下方式运行 Java8Tester −
Now run the Java8Tester as follows −
C:\JAVA>java Java8Tester
它应该产生以下输出 −
It should produce the following output −
Print all numbers:
1
2
3
4
5
6
7
8
9
Print even numbers:
2
4
6
8
Print numbers greater than 3:
4
5
6
7
8
9