Function.identity()

作者: 不知名的蛋挞 | 来源:发表于2018-11-04 12:46 被阅读1046次

    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来让上面的代码代码变得更简洁明了、传递开发者意图时更加直接,下面是采用identity函数的代码。

    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() 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 -> strFunction.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没有关系

    相关文章

      网友评论

        本文标题:Function.identity()

        本文链接:https://www.haomeiwen.com/subject/sxygtqtx.html