Predicate示例
Predicate简介
- Predicate用于分配lambda表达式。
- functional interface为功能性接口(函数式接口),有此注解的接口类只有一个对外接口方法。Predicate的接口为test(T t)。
- 当我们将对象传递至这个方法时,它将通过分配的lambda表达式来评估对象。语法介绍:
public static void main (String[] args) {
// 接受一个泛型参数,比较返回boolean值。
Predicate<String> predicate = (v1) -> v1.equals("1");
System.out.println(predicate.test("1"));
System.out.println(predicate.test("2"));
}
可见Predicate代码如下。test方法的参数为泛型,创建Predicate对象时,可利用lambda书写test方法的逻辑。
@FunctionalInterface
public interface Predicate<T> {
/**
* Evaluates this predicate on the given argument.
*
* @param t the input argument
* @return {@code true} if the input argument matches the predicate,
* otherwise {@code false}
*/
boolean test(T t);
}
Predicate实例
public static void main(String[] args) {
Predicate<String> predicate = value -> value.equals("Amy");
if (predicate.test("Amy")) {
sout("Hello");
}
}
// Hello
Function示例
Function-demo
public class FunctionTest {
public static void main(String[] args) {
FunctionTest test = new FunctionTest();
System.out.println(test.method1(1, value -> value * 2, value -> value - 9));
System.out.println(test.method2(1, value -> value * 2, value -> value - 9));
System.out.println(test.method3(3, 4, (a, b) -> a + b));
System.out.println(test.method4(2, 3, (a, b) -> a + b, value -> value - 10086));
}
public int method1(int count, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.compose(function2).apply(count);
}
public int method2(int count, Function<Integer, Integer> function1, Function<Integer, Integer> function2) {
return function1.andThen(function2).apply(count);
}
public int method3(int a, int b, BiFunction<Integer, Integer, Integer> biFunction) {
return biFunction.apply(a, b);
}
public int method4(int a, int b, BiFunction<Integer, Integer, Integer> biFunction, Function<Integer, Integer> function) {
// 因为BiFunction有两个变量,Function入参只有一个,所以BiFunction只有andThen这个方法,没有compose方法,且andThen参数为Function。
return biFunction.andThen(function).apply(a, b);
}
}
// 结果 -16 -9 7 -10081
// 其中compose为先将count传入function2,将返回的结果作为function1的参数。andThen反之。
// BiFunciton用于接收多个参数。