1 Function
@FunctionalInterface
public interface Function<T, R> {
/**
* Applies this function to the given argument.
*
* @param t the function argument
* @return the function result
*/
R apply(T t);
- 接受一个T,返回一个R
eg:接受一个String,返回Sting对应的hashCode
@Test
public void testFunction(){
Function<String,Integer> hashCode = (p1)->p1.hashCode();
Integer result = hashCode.apply("java");
System.out.println(result);
}
又比如:接受一个int,返回该数的平方
@Test
public void testFunction2(){
Function<Integer,Double> hashCode = p1->Math.pow(p1,2);
Double result = hashCode.apply(2);
System.out.println(result);
}
2 IntFunction,LongFunction,DoubleFunction等
@FunctionalInterface
public interface IntFunction<R> {
/**
* Applies this function to the given argument.
*
* @param value the function argument
* @return the function result
*/
R apply(int value);
}
- 和之前的LongPredicate,Function也有类似这样一系列的函数式接口(LongFunction,IntFunction),只是明确规定T的类型为int类型而已,只需要声明返回值类型即可
@Test
public void testIntFunction2(){
IntFunction<Double> hashCode = p1->Math.pow(p1,2);
Double result = hashCode.apply(2);
System.out.println(result);
}
3 BiFunction
@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);
- 接受T, U两种类型,返回R类型
eg: 简单来说可以用求两数之和
@Test
public void testBiFunction(){
BiFunction<Integer,Integer,Integer> sumFunction = (a,b)->a+b;
Integer sum = sumFunction.apply(1, 2);
System.out.println(sum);
}
4 ToDoubleBiFunction
@FunctionalInterface
public interface ToDoubleBiFunction<T, U> {
/**
* Applies this function to the given arguments.
*
* @param t the first function argument
* @param u the second function argument
* @return the function result
*/
double applyAsDouble(T t, U u);
}
- 说白了就是明确了返回值类型为Double,类似有ToIntBiFunction,ToLongBiFunction,ToDoubleFunction,ToIntFunction,ToLongFunction
@Test
public void testToDoubleBiFunction(){
// 计算 a的b次方
ToDoubleBiFunction<Integer,Integer> doubleBiFunction = (a,b)->Math.pow(a,b);
double result = doubleBiFunction.applyAsDouble(2, 3);
System.out.println(result);
}