@FunctionalInterface使用和自定义
@FunctionalInterface使用和自定义
这个是java1.8加入的新特性,这个有时候有时候业务重复单对象不重复是,这时函数是编程就能解决这个问题,相当于回调函数,可以让参数方法里外传来去。
例子
使用已有的函数对象
@FunctionalInterface
public interface BiFunction<T, U, R> {
/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
R apply(T t, U u);
/**
* Returns a composed function that first applies this function to
* its input, and then applies the {@code after} function to the result.
* If evaluation of either function throws an exception, it is relayed to
* the caller of the composed function.
*
* @param <V> the type of output of the {@code after} function, and of the
* composed function
* @param after the function to apply after this function is applied
* @return a composed function that first applies this function and then
* applies the {@code after} function
* @throws NullPointerException if after is null
*/
default <V> BiFunction<T, U, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t, U u) -> after.apply(apply(t, u));
}
}
使用方式
public static void main(String[] args) {
BiFunction<Integer, Long, String> a = (t, u) -> String.valueOf(t+u);
System.out.println(a.apply(1,2L));
}
这是java1.8提供的所有函数,可以自行研究,如果不够我们还可以自定义

自定义函数
定义函数
@FunctionalInterface
public interface ZkqFunction<Z,K,Q> {
/**
* Applies this function to the given arguments.
* @param z 第一个参数
* @param k 第二个参数
* @return Q 返回值
*/
Q zkq(Z z,K k);
}
使用函数
public static void main(String[] args) {
ZkqFunction<String,String,String> zk = (z,k) -> z+k+"q";
System.out.println(zk.zkq("z","k"));
}
输出
zkq
var code = “e05eb0e0-9237-4c84-8aef-0609e1b413e3”
浙公网安备 33010602011771号