java8新特性之Function.identity()

Function.identity()是什么?

// 将Stream转换成容器或Map
Stream<String> stream = Stream.of("I", "love", "you", "too");
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源码如下:

static  Function identity() {
    return t -> t;
}

Function.identity()的应用
下面的代码中,Task::getTitle需要一个task并产生一个仅有一个标题的key。task -> task是一个用来返回自己的lambda表达式,上例中返回一个task。

private static Map<String, Task> taskMap(List<Task> tasks) {
  return tasks.stream().collect(toMap(Task::getTitle, task -> task));
}

Function.identity() or t->t?

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 -> str和Function.identity()是没什么区别的因为它们都是t->t。但是我们有时候不能使用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没有关系。

(实际应用:)

参考:https://www.jianshu.com/p/cd694d2d8be5

  • 12
    点赞
  • 37
    收藏
    觉得还不错? 一键收藏
  • 1
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论 1
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值