Java 8 identity function Function.identity() returns a Function that always returns it’s input argument.
和f(x)=x一个意思
public class Java8FunctionIdentityExample1 {
public static void main(String[] args) {
Function<Integer, Integer> identityFunction = Function.identity();
Function<Integer, Integer> intFunction = e -> e; // using lambda expression
System.out.println(identityFunction.apply(10)); // 10
System.out.println(intFunction.apply(10)); // 10
List<String> names = Arrays.asList(
"Peter",
"Martin",
"John",
"Vijay",
"Arthur"
);
// Just for example
System.out.println("----- Function.identity() -----");
names.stream().map(Function.identity()).forEach(System.out::println);
System.out.println("----- Function(e-> e) -----");
names.stream().map(e->e).forEach(System.out::println);
}
}
Output
10
10
----- Function.identity() -----
Peter
Martin
John
Vijay
Arthur
----- Function(e-> e) -----
Peter
Martin
John
Vijay
Arthur
源码
@FunctionalInterface
public interface Function<T, R> {
//....
// 静态方法 (Java 8允许在接口中加入具体方法。接口中的具体方法有两种,default方法和static方法)
// 返回一个Function对象,即lambda表达式对象
static Function identity() {
return t -> t;
}
}
什么时候会用到这个方法??我疑惑
当我们使用Stream时,要将它转换成其他容器或Map。这时候,就会使用到Function.identity()。
Stream<String> stream = Stream.of("This", "is", "a", "test");
Map<String, Integer> map = stream.collect(Collectors.toMap(Function.identity(), String::length));
注意有时候不能用它代替i -> i
有时候不能使用Function.identity,看下面的例子:
List list = new ArrayList<>();
list.add(1);
list.add(2);
下面这段代码可以运行成功:
int[] arrayOK = list.stream().mapToInt(i -> i).toArray();
但是如果你像下面这样写:
int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();
运行的时候就会错误,因为mapToInt要求的参数是ToIntFunction类型,但是ToIntFunction类型和Function没有关系。