我是靠谱客的博主 安详口红,这篇文章主要介绍Function.identity()的使用详解,现在分享给大家,希望可以做个参考。

一、Function.identity()简单介绍

当我们使用Stream时,要将它转换成其他容器或Map。这时候,就会使用到Function.identity()

复制代码
1
2
3
Stream<String> stream = Stream.of("This", "is", "a", "test"); Map<String, Integer> map = stream.collect(Collectors.toMap(Function.identity(), String::length));

Function是一个接口,那么Function.identity()是什么意思呢?解释如下:

Java 8允许在接口中加入具体方法。接口中的具体方法有两种,default方法static方法identity()就是Function接口的一个静态方法。
Function.identity()返回一个输出跟输入一样的Lambda表达式对象,等价于形如t -> t形式的Lambda表达式。

identity()方法JDK源码如下:

复制代码
1
2
3
4
static Function identity() { return t -> t; }

二、Function.identity()的应用

下面的代码中,Task::getTitle需要一个task并产生一个仅有一个标题的key。task -> task是一个用来返回自己的lambda表达式,根据上例,可以得知会返回一个task。

复制代码
1
2
3
4
private static Map<String, Task> taskMap(List<Task> tasks) { return tasks.stream().collect(toMap(Task::getTitle, task -> task)); }

可以使用Function接口中的默认方法identity来让上面的代码代码变得更简洁明了、传递开发者意图时更加直接,下面是采用identity函数的代码。

复制代码
1
2
3
4
5
6
import static java.util.function.Function.identity; private static Map<String, Task> taskMap(List<Task> tasks) { return tasks.stream().collect(toMap(Task::getTitle, identity())); }

三、Function.identity() 和 t->t的选择

复制代码
1
2
3
4
5
6
7
8
Arrays.asList("a", "b", "c") .stream() .map(Function.identity()) // <- This, .map(str -> str) // <- is the same as this. .collect(Collectors.toMap( Function.identity(), // <-- And this, str -> str)); // <-- is the same as this.

上面的代码中,为什么要使用Function.identity()代替str->str呢?它们有什么区别呢?

在上面的代码中str -> strFunction.identity()是没什么区别的因为它们都是t->t。但是我们有时候不能使用Function.identity,看下面的例子:

复制代码
1
2
3
4
List list = new ArrayList<>(); list.add(1); list.add(2);

下面这段代码可以运行成功:

复制代码
1
2
int[] arrayOK = list.stream().mapToInt(i -> i).toArray();

但是如果你像下面这样写:

复制代码
1
2
int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();

运行的时候就会错误,因为mapToInt要求的参数是ToIntFunction类型,但是ToIntFunction类型和Function没有关系。

最后

以上就是安详口红最近收集整理的关于Function.identity()的使用详解的全部内容,更多相关Function.identity()内容请搜索靠谱客的其他文章。

本图文内容来源于网友提供,作为学习参考使用,或来自网络收集整理,版权属于原作者所有。
点赞(56)

评论列表共有 0 条评论

立即
投稿
返回
顶部