一、介绍
在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} } }