• Java——Stream map


    一、介绍

    在Java 8中,Stream的map方法可以将对象转化为其他对象。

    二、例子

    2.1、大写字符串列表

    List<String> list = new ArrayList<>();
    Collections.addAll(list, "a", "b", "c");
    list = list.stream().map(String::toUpperCase).collect(Collectors.toList());
    System.out.println(list);   // [A, B, C]
    

    2.2、对象列表 -> 字符串列表

    List<Student> list = new ArrayList<>();
    Student stu1 = new Student("张三", 10);
    Student stu2 = new Student("李四", 30);
    Student stu3 = new Student("王五", 20);
    Collections.addAll(list, stu1, stu2 ,stu3);
    List<String> newList = list.stream().map(stu -> stu.getName()).collect(Collectors.toList());
    System.out.println(newList);   // [张三, 李四, 王五]
    

    2.3、对象列表 -> 其他对象列表

    // Student.java
    public class Student {
        private String name;
        private int age;
        //...
    }
    
    
    // Teacher.java
    public class Teacher {
        private String name;
        private int age;
        //...
    }
    
    // StreamMap.java
    public class StreamMap {
        public static void main(String[] args) {
            List<Student> list = new ArrayList<>();
            Student stu1 = new Student("张三", 24);
            Student stu2 = new Student("李四", 22);
            Student stu3 = new Student("王五", 25);
            Collections.addAll(list, stu1, stu2, stu3);
            List<Teacher> teacList = list.stream().map(stu -> {
               String name = stu.getName();
               int age = stu.getAge();
               return new Teacher(name, age);
            }).collect(Collectors.toList());
            teacList.stream().forEach(stu -> System.out.println(stu));
            //Teacher{name='张三', age=24}
            //Teacher{name='李四', age=22}
            //Teacher{name='王五', age=25}
        }
    }
    

      

      

  • 相关阅读:
    [leetcode] Combinations
    [leetcode] Search for a Range
    [leetcode] Combination Sum II
    [leetcode] Combination Sum
    [leetcode] Reverse Bits
    [leetcode] Number of 1 Bits
    [leetcode] Longest Substring Without Repeating Characters
    [leetcode] Reverse Words in a String
    [leetcode] Rotate Array
    习题8-3 数组循环右移
  • 原文地址:https://www.cnblogs.com/xulinjun/p/14804097.html
Copyright © 2020-2023  润新知