zoukankan      html  css  js  c++  java
  • 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);
            });

  • 相关阅读:
    js如何获取当天日期的开始时间和结束时间
    bootstrapTable 刷新数据
    vue全家桶
    JavaScript数组是否存在及是否存在某个元素
    asp.net core 负载均衡集群搭建(centos7+nginx+supervisor+kestrel)
    (转) 将ASP.NET Core应用程序部署至生产环境中(CentOS7)
    mysql 5.7 docker 主从复制架构搭建
    CentOS6.x生产环境下一键安装mono+jexus的脚本,自启动,带服务,版本号自控
    使用 Json.Net 对Json文本进行 增删改查
    C# dynamic 动态创建 json
  • 原文地址:https://www.cnblogs.com/dalianpai/p/12611247.html
Copyright © 2011-2022 走看看