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

使用条件:

输入与输出相同时可代替Lambda 表达式提高阅读性

package com.demo;

public class Test2 {

    public static void main(String[] args) {
        Student s = new Student("张三", 18, "唱歌");
        Student s1 = new Student("李四", 27, "跳舞");
        Student s2 = new Student("王五", 26, "学习JAVA");
        Student s3 = new Student("旺财", 11, "LOL");
        Student s4 = new Student("旺财", 12, "唱歌");
        Student s5 = new Student("旺财", 13, "学习JAVA");

        List<Student> studens = new ArrayList<Student>();
        studens.add(s);
        studens.add(s1);
        studens.add(s2);
        studens.add(s3);
        studens.add(s4);
        studens.add(s5);

        //将list转换为map,key为学生的age,值为学生对象

        //实现方式一:lambda
        Map<Integer, Student> collect1 = studens.stream().collect(Collectors.toMap(listStu -> listStu.getAge(), t -> t));
        //实现方式二:
        Map<Integer, Student> collect = studens.stream().collect(Collectors.toMap(Student::getAge, Function.identity()));
        System.out.println(collect);
    }
}

}


/*
{18=Student{name='张三', age=18, hobby='唱歌'}, 26=Student{name='王五', age=26, hobby='学习JAVA'}, 27=Student{name='李四', age=27, hobby='跳舞'}, 11=Student{name='旺财', age=11, hobby='LOL'}, 12=Student{name='旺财', age=12, hobby='唱歌'}, 13=Student{name='旺财', age=13, hobby='学习JAVA'}}
*/

https://www.jb51.net/program/285983obz.htm

posted @ 2023-12-13 20:54  chuangzhou  阅读(415)  评论(0编辑  收藏  举报