package com.test.jdk8;
import java.util.function.*;
public class FunctionalInterfaceTest {
public static void main(String[] args) {
testFunctionInterface();
testOperationFnInterface();
}
private static void testFunctionInterface() {
System.out.println("自带的函数式接口");
//Consumer<T> - T作为输入,执行某种动作但没有返回值
Consumer<String> con = (x) -> {
System.out.println(x);
};
con.accept("hello world");
//Supplier<T> - 没有任何输入,返回T
Supplier<String> supp = () -> {
return "Supplier";
};
System.out.println(supp.get());
//Predicate<T> -T作为输入,返回的boolean值作为输出
Predicate<String> pre = (x) -> {
System.out.print(x);
return x.startsWith("op");
};
System.out.println(": " + pre.test("op, hello World"));
// Function<T, R> -T作为输入,返回的R作为输出
Function<String, String> function = (x) -> {
System.out.print(x + ": ");
return "Function";
};
System.out.println(function.apply("hello world"));
//BinaryOperator<T> -两个T作为输入,返回一个T作为输出,对于“reduce”操作很有用
BinaryOperator<String> bina = (x, y) -> {
System.out.print(x + " " + y);
return "BinaryOperator";
};
System.out.println(" " + bina.apply("hello ", "world"));
System.out.println();
}
private static void testOperationFnInterface() {
System.out.println("使用CalcInterface");
CalcInterface<Integer, Integer> addOper1 = (n1, n2) -> {
return n1 + n2;
};
CalcInterface<Integer, Integer> multiOper1 = (n1, n2) -> {
return n1 * n2;
};
NumberOperation<Integer, Integer> np = new NumberOperation(13, 10);
System.out.println(np.calc1(addOper1));
System.out.println(np.calc1(multiOper1));
System.out.println(np.calc1((n1, n2) -> n1 + n2));
System.out.println(np.calc1((n1, n2) -> n1 * n2));
System.out.println();
System.out.println("使用BinaryOperator");
BinaryOperator<Integer> addOper2 = (n1, n2) -> {
return n1 + n2;
};
BinaryOperator<Integer> multiOper2 = (n1, n2) -> {
return n1 * n2;
};
System.out.println(np.calc2(addOper2));
System.out.println(np.calc2(multiOper2));
}
@FunctionalInterface
public interface CalcInterface<N, V> {
V operation(N n1, N n2);
}
public static class NumberOperation<N extends Number, V extends Number> {
private N n1;
private N n2;
public NumberOperation(N n1, N n2) {
this.n1 = n1;
this.n2 = n2;
}
public V calc1(CalcInterface<N, V> ci) {
V v = ci.operation(n1, n2);
return v;
}
public N calc2(BinaryOperator<N> ci) {
N v = ci.apply(n1, n2);
return v;
}
}
}