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

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

关于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

标签:Java8,Function,identity()
0
投稿

猜你喜欢

  • Spring Boot修改启动端口的方法

    2022-02-10 05:49:55
  • Android WindowManger实现桌面悬浮窗功能

    2023-08-01 02:16:10
  • 简单聊一聊Java线程池ThreadPoolExecutor

    2021-10-23 15:56:58
  • Springboot JPA 枚举Enum类型存入到数据库的操作

    2023-11-25 16:11:40
  • Java 回调callback举例详解

    2023-11-11 16:25:09
  • SpringBoot+Mybatis项目使用Redis做Mybatis的二级缓存的方法

    2021-06-17 20:09:50
  • 详解Spring Boot集成MyBatis(注解方式)

    2023-10-03 17:45:47
  • C#中通过Command模式实现Redo/Undo方案

    2021-07-12 14:58:59
  • 使用Spring Data JDBC实现DDD聚合的示例代码

    2022-05-04 05:11:23
  • Java实战之基于swing的QQ邮件收发功能实现

    2023-11-15 01:34:26
  • Java线程池submit阻塞获取结果的实现原理详解

    2021-08-29 03:55:45
  • 史上最全的java随机数生成算法分享

    2023-10-17 15:22:33
  • Maven+SSM框架实现简单的增删改查

    2023-11-16 17:14:38
  • flutter中使用流式布局示例详解

    2023-08-24 23:49:06
  • Spring Security OAuth2 实现登录互踢的示例代码

    2023-09-04 19:09:28
  • vue+springboot前后端分离工程跨域问题解决方案解析

    2023-08-06 06:51:10
  • Java基础知识之CharArrayReader流的使用

    2023-02-12 10:40:29
  • 如何用120行Java代码写一个自己的区块链

    2023-07-17 03:44:33
  • SpringCloud消息总线Bus配置中心实现过程解析

    2023-02-14 10:05:18
  • SpringBoot中@Import注解如何正确使用

    2023-07-28 12:36:16
  • asp之家 软件编程 m.aspxhome.com