首先上Function接口的identity方法的代码,
@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);
/...../
static <T> Function<T, T> identity() {
return t -> t;
}
}
先看看函数式接口概念,只有一个自定义方法的接口就是函数式接口,当然最好加上FunctionalInterfac注解。
这里的自定义方法就是apply(),这是主角,整个函数式接口的主角。从测试来看只要你当前只申明了一个自定义方法,就可以
从返回看identity方法返回了一个<T,T>匿名内部类即入参和返回类型是一样的,于是再看return t->t;这就是使用lambda创建了一个匿名内部类,t->t就是apply方法的实现。直接返回applay的入参t;
也就是在接口的defualt 方法,和static方法中都可以使用lambda表达式。
结论:identity方法就是创建了一个函数接口直接返回参数本身的一个Function实例。
identity的example,copy from http://www.java2s.com/.有梯子的小伙伴肯定喜欢,。
全路径http://www.java2s.com/Tutorials/Java/java.util.function/Function/1080__Function.identity.htm。
Example
The following example shows how to use identity.
import java.util.function.Function;
/*w w w . ja v a 2 s. co m*/
public class Main {
public static void main(String[] args) {
Function<Integer,Integer> id = Function.identity();
System.out.println(id.apply(3));
}
}
The code above generates the following result.
example2
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Function;
/* w ww. ja va 2 s .c o m*/
public class Main {
public static void main(String[] args) {
Function<Double, Double> square = number -> number * number;
Function<Double, Double> half = number -> number * 2;
List<Double> numbers = Arrays.asList(10D, 4D, 12D);
// you can use identity to not modify them
System.out.println(mapIt(numbers, Function.<Double>identity()));
}
private static List<Double> mapIt(List<Double> numbers, Function<Double, Double> fx) {
List<Double> result = new ArrayList<>();
for (Double number : numbers) {
result.add(fx.apply(number));
}
return result;
}
}