一、Function.identity()简单介绍
当我们使用Stream
时,要将它转换成其他容器或Map。这时候,就会使用到Function.identity()
。
1
2
3Stream<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
4static Function identity() { return t -> t; }
二、Function.identity()的应用
下面的代码中,Task::getTitle
需要一个task并产生一个仅有一个标题的key。task -> task
是一个用来返回自己的lambda表达式,根据上例,可以得知会返回一个task。
1
2
3
4private 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
6import 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
8Arrays.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 -> str
和Function.identity()
是没什么区别的因为它们都是t->t
。但是我们有时候不能使用Function.identity
,看下面的例子:
1
2
3
4List list = new ArrayList<>(); list.add(1); list.add(2);
下面这段代码可以运行成功:
1
2int[] arrayOK = list.stream().mapToInt(i -> i).toArray();
但是如果你像下面这样写:
1
2int[] arrayProblem = list.stream().mapToInt(Function.identity()).toArray();
运行的时候就会错误,因为mapToInt
要求的参数是ToIntFunction
类型,但是ToIntFunction
类型和Function
没有关系。
最后
以上就是安详口红最近收集整理的关于Function.identity()的使用详解的全部内容,更多相关Function.identity()内容请搜索靠谱客的其他文章。
发表评论 取消回复