软件编程
位置:首页>> 软件编程>> java编程>> Java8中关于Function.identity()的使用

Java8中关于Function.identity()的使用

作者:ACGkaka_  发布时间:2021-11-16 16:05:15 

标签:Java8,Function,identity()

关于Function.identity()的使用

简单介绍

话不多说,直接上JDK源码:

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

我们可以看到,Function.identity() 的作用就是 获取一个直接返回入参的函数。

补充:Java8 允许再接口中加入具体方法。接口中的具体方法有两种:default方法static方法

identify() 就是 Function 接口的一个 static 方法。

使用示例

当我们使用 Stream 想要将集合的某一属性(例如手机号)作为 key,对象本身作为 value 时,就可以在 Collectors.toMap() 中配合使用 Function.identity()。

// 查询数据
List<UserInfo> list = userInfoMapper.getList();
// 获取 手机号-UserInfo 映射
Map<String, UserInfo> phoneNumberMap = list.stream().collect(Collectors.toMap(UserInfo::getPhoneNumber(), Function.identity(), (v1, v2) -> v1));

不适用场景

不适用于 mapToInt()mapToLong()mapToDouble() 等需要进行拆箱操作的场景。

public static void main(String[] args) {
List<Integer> list = Arrays.asList(1, 2, 3);
int[] array = list.stream().mapToInt(Function.identity()).toArray();
System.out.println(array.length);
}

Java8中关于Function.identity()的使用

因为这三个方法的入参并不是 Function 类型,而是 ToIntFunciton、ToLongFunction、ToDoubleFunction。

Java8中关于Function.identity()的使用

Function.identity()的含义

Java 8允许在接口中加入具体方法。

接口中的具体方法有两种,default方法和static方法.

identity()就是Function接口的一个静态方法。

Function.identity()返回一个输出跟输入一样的Lambda表达式对象,等价于形如t -> t形式的Lambda表达式

    private static void identity() {
        Stream<String> stream = Stream.of("I", "love", "you", "too");
        Map<String, Integer> map = stream.collect(Collectors.toMap(Function.identity(), String::length));
        System.out.println(map);
    }

输出结果为:

 {love=4, too=3, I=1, you=3}

来源:https://blog.csdn.net/qq_33204709/article/details/128056675

0
投稿

猜你喜欢

手机版 软件编程 asp之家 www.aspxhome.com