一、函数式接口
function接口:
package java.util.function;
import java.util.Objects;
@FunctionalInterface
public interface Function<T, R> {
/**
* 将Function对象应用到输入的参数上,然后返回计算结果。
*/
R apply(T t);
/**
* 返回一个先执行before函数对象apply方法再执行当前函数对象apply方法的函数对象。
*/
default <V> Function<V, R> compose(Function<? super V, ? extends T> before) {
Objects.requireNonNull(before);
return (V v) -> apply(before.apply(v));
}
/**
* 返回一个先执行当前函数对象apply方法再执行after函数对象apply方法的函数对象。
*/
default <V> Function<T, V> andThen(Function<? super R, ? extends V> after) {
Objects.requireNonNull(after);
return (T t) -> after.apply(apply(t));
}
/**
* 返回一个执行了apply()方法之后只会返回输入参数的函数对象。
*/
static <T> Function<T, T> identity() {
return t -> t;
}
}
二、使用示例
/**
* @author Kevin
* @date 2017-01-26
*/
public class FunctionTest {
public static void main(String[] args) {
int a = 3;
int b = 7;
mathOperation(a, value -> value + b);
a = 9;
mathOperation(a, value -> value * b);
}
/**
* 数学计算
*
* @author Kevin
*/
private static void mathOperation(int value, Function<Integer, Integer> function) {
int result = function.apply(value);
System.out.println(result);
}
}