Function.identity()的含义
偶然之间发现的这个函数,感觉还是很有用的,尤其实在返回map的时候,value还为本身,用起来就很方便。
Java 8允许在接口中加入具体方法。接口中的具体方法有两种,default方法和static方法,identity()就是Function接口的一个静态方法。
Function.identity()返回一个输出跟输入一样的Lambda表达式对象,等价于形如t -> t
形式的Lambda表达式
@Test public void test() { List<Person> personList = new ArrayList<>(); personList.add(new Person("hepengju", 28, 20000.0)); personList.add(new Person("lisi" , 44, 40000.0)); personList.add(new Person("wangwu" , 55, 50000.0)); personList.add(new Person("zhaoliu" , 66, 60000.0)); personList.add(new Person("zhangsan", 33, 33333.0)); personList.add(new Person("wgr", 23, 10000.0)); Map<String, Person> collect = personList.stream().collect(Collectors.toMap(Person::getName, Function.identity())); collect.forEach((name,p) ->{ System.out.println(name + ":"+p); }); }
但是改成同一个名字的时候就会报错
修改如下:
@Test public void test() { List<Person> personList = new ArrayList<>(); personList.add(new Person("hepengju", 28, 20000.0)); personList.add(new Person("lisi" , 44, 40000.0)); personList.add(new Person("wangwu" , 55, 50000.0)); personList.add(new Person("zhaoliu" , 66, 60000.0)); personList.add(new Person("zhangsan", 33, 33333.0)); personList.add(new Person("zhangsan", 23, 10000.0)); ConcurrentHashMap<String, Person> collect = personList.stream().collect(Collectors.toMap(Person::getName, Function.identity(), (o1, o2) -> o1, ConcurrentHashMap::new)); collect.forEach((name,p) ->{ System.out.println(name + ":"+p); });
如果想返回 Map<String, Map<Integer, Person>>,可以这样写。
Map<String, Map<Integer, Person>> collect = personList.stream().collect(Collectors.toMap(Person::getName, p -> { Map<Integer, Person> map = new HashMap<>(); map.put(p.getAge(), p); return map; })); collect.forEach( (name,p) ->{ System.out.println(name + ":"+p); });
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· Linux系列:如何用heaptrack跟踪.NET程序的非托管内存泄露
· 开发者必知的日志记录最佳实践
· SQL Server 2025 AI相关能力初探
· Linux系列:如何用 C#调用 C方法造成内存泄露
· AI与.NET技术实操系列(二):开始使用ML.NET
· 无需6万激活码!GitHub神秘组织3小时极速复刻Manus,手把手教你使用OpenManus搭建本
· C#/.NET/.NET Core优秀项目和框架2025年2月简报
· 葡萄城 AI 搜索升级:DeepSeek 加持,客户体验更智能
· 什么是nginx的强缓存和协商缓存
· 一文读懂知识蒸馏