Java Stream中map、flatMap 的使用区别

581 阅读2分钟

携手创作,共同成长!这是我参与「掘金日新计划 · 8 月更文挑战」的第7天,点击查看活动详情

map

map是对stream流中的每个数据进行操作,一般用于类型转换、或者是结果映射,例如一个学生信息数据流,如果要获取所有学生的name属性,可以使用map操作,代码示例:

学生信息:

public class Student{
    private String name;
    private Long id;
    private String address;
    ......
}

如果是stream出现之前,要获取所有学生的name,需要循环处理:

public class Demo{
    public static void main(String[] args) {
        Student student1 = new Student("xiaoming",1,"beijing");
        Student student2 = new Student("xiaohong",2,"shandong");
        ...
        List<Student> studentList = Lists.asList(student1,student2,...);
        
        List<String> allStudentNameList = new ArrayList<>();
        for(int i = 0;i < studentList.size(); i++){
            allStudentNameList.add(studentList.get(i).getName());
        }
    }
}

在出现了stream之后,处理方式可以修改为:

public class Demo{
    public static void main(String[] args) {
        Student student1 = new Student("xiaoming",1,"beijing");
        Student student2 = new Student("xiaohong",2,"shandong");
        ...
        List<Student> studentList = Lists.asList(student1,student2,...);
        
        List<String> allStudentNameList = studentList.stream().map(Student::getName).collect(Collectors.toList());
    }
}

可以看到,繁琐的循环变为了一行代码就返回了想要的结果,其中的逻辑顺序是将List转换为Stream数据流,再由map()方法取数据流中每个数据的name属性,Student::getName是简化写法,等于:o->o.getName();最后再由Collectors收集为List返回。

flatMap

flatMap与map有相同也有不同,相同的是都是对stream数据流中的每个数据进行处理,不同的是,map是处理每个数据转换为另一种数据类型的输出值,而flatMap可以处理每个数据转换为任意数量个他类型的输出值。代码示例:

public class Demo {
    public static void main(String[] args) {
    String[] address = {"beijing", "nanjing","shanghai",...};

    List addressList = Arrays.asList(address).stream().
          map(string -> string.split("")).
          flatMap(string -> Arrays.stream(string))
          .collect(Collectors.toList());
    addressList.stream().forEach(System.out::printlv);
  }
}

首先也是先将List数据转换为了stream数据流,然后使用了map将每个数据转换为了String[]类型,此时Stream中的数据类型也由String变为了String[],接着再由flatMap将多个Stream<String[]>都合为了一个Stream<String[]>,最后由Collectors收集为List返回。