今天聊聊一些Functional interfaces,也就是一些函数式接口。本文介绍从Java 1.8开始的新的Functional interfaces。
在Java 1.8以前就有Functional interfaces,比如java.lang.Runnable,java.util.Comparator,etc。在1.8里,又有一些新的interface被引入,它们都在package java.util.function下面。
官方文档里面对java.util.function的描写:
Functional interfaces provide target types for lambda expressions and method references. Each functional interface has a single abstract method, called the functional method for that functional interface, to which the lambda expression's parameter and return types are matched or adapted. Functional interfaces can provide a target type in multiple contexts, such as assignment context, method invocation, or cast context.
java.util.function里面常用的interface:
- Predicate -- 传入一个参数,返回一个boolean结果, 方法为boolean test(T t)
- Consumer -- 传入一个参数,无返回值,纯消费。 方法为void accept(T t)
- Function -- 传入一个参数,返回一个结果,方法为R apply(T t)
- Supplier -- 无参数传入,返回一个结果,方法为T get()
Predicate
Predicate代表的是有判断功能的function。
public class Test {
public static void main(String[] args) {
String name1 = "";
String name2 = "012345";
System.out.println("Result of the 1st example: " + validInput(name1, input -> input.isEmpty()));
System.out.println("Result of the 2nd example: " + validInput(name2, input -> input.length() > 3));
}
public static boolean validInput(String name, Predicate<String> criteria) {
return criteria.test(name);
}
}
返回结果:
Result of the 1st example: true
Result of the 2nd example: true
Predicate的其他method包括:
- and(Predicate<? super T> other) -- 返回一个复合的Predicate,只有当两个Predicate都判断为true时,最后结果才为true,相当于AND。
- or(Predicate<? super T> other) -- 返回一个复合的Predicate,只要有一个Predicate判断为true,最后结果为true,相当于OR。
...
Function
public class Test {
public static void main(String[] args) {
int number = 12345;
number = validInput(number, x -> {
x = x / 100;
System.out.println("number is " + x);
return x;
});
System.out.println("current number is " + number);
}
public static int validInput(int number, Function<Integer,Integer> function) {
return function.apply(number);
}
}
返回结果:
number is 123
current number is 123
Consumer
public class Test {
public static void main(String[] args) {
int number = 12345;
validInput(number, x -> {
System.out.println("number is " + x / 100);
return;
});
System.out.println("current number is " + number);
}
public static void validInput(int number, Consumer<Integer> function) {
function.accept(number);
}
}
返回结果:
number is 123
current number is 12345
To be continued...
网友评论