JAVA8-Lambda-map (元素转换)

功能:元素转换

代码示例一:

    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("张三", 9, "杭州"));
        list.add(new Student("李四", 8, "海口"));
        list.add(new Student("王五", 7, "西安"));
        list.add(new Student("赵六", 6, "兰州"));
        //map方法可以帮我们做元素转换,比如今天是元旦新的一年开始了让所有孩子的虚岁+1
        List<Student> studentList = list.stream().map(student -> ageAddOne(student)).collect(Collectors.toList());
        System.out.println(studentList);
    }

    private static Student ageAddOne(Student student) {
        student.setAge(student.getAge() + 1);
        return student;
    }

结果:(结果中所有孩子的年龄都+1)

代码示例二:

    public static void main(String[] args) {
        ArrayList<Student> list = new ArrayList<>();
        list.add(new Student("张三", 9, "杭州"));
        list.add(new Student("李四", 8, "海口"));
        list.add(new Student("王五", 7, "西安"));
        list.add(new Student("赵六", 6, "兰州"));
        // 获取所有孩子的名字,转换为一个名字列表。
        List<String> nameList = list.stream().map(student -> student.getName()).collect(Collectors.toList());
        System.out.println(nameList);
    }

结果:

posted @ 2022-11-06 10:28  CodeLuckly  阅读(464)  评论(0编辑  收藏  举报