前言
对于刚刚接触stream中的小伙伴,可能都有个疑惑,那就是map和flatMap到底有啥区别,这里来和大家一起简单复习下。
举个小栗子
public class StreamTest {
private static List<Student> computerClub = Arrays.asList(
new Student("2015134001", "小明", 15, "1501"),
new Student("2015134003", "小王", 14, "1503"),
new Student("2015134006", "小张", 15, "1501"),
new Student("2015134008", "小梁", 17, "1505")
);
private static List<Student> basketballClub = Arrays.asList(
new Student("2015134012", "小c", 13, "1503"),
new Student("2015134013", "小s", 14, "1503"),
new Student("2015134015", "小d", 15, "1504"),
new Student("2015134018", "小y", 16, "1505")
);
private static List<Student> pingpongClub = Arrays.asList(
new Student("2015134022", "小u", 16, "1502"),
new Student("2015134021", "小i", 14, "1502"),
new Student("2015134026", "小m", 17, "1504"),
new Student("2015134027", "小n", 16, "1504")
);
private static List<List<Student>> allClubStu = new ArrayList<>();
public static void main(String[] args) {
//map 一对一 映射处理
collect.stream().map(student -> {
StudentDTO studentDTO = StudentDTO.builder().age(student.getAge())
.classNum(student.getClassNum())
.name(student.getName())
.studentNum(student.getStudentNum()).build();
return studentDTO;
}).collect(Collectors.toList()).forEach(System.out::println);
allClubStu.add(computerClub);
allClubStu.add(basketballClub);
allClubStu.add(pingpongClub);
//flatMap 一对多映射处理,深入到多个stream内部去处理子元素,统一输出
List<Student> studentList = allClubStu.stream().flatMap(e -> e.stream().
filter(student -> student.getAge() > 15)).collect(Collectors.toList());
studentList.forEach(System.out::println);
}
}
简而言之
map: 对于Stream中包含的元素使用给定的转换函数进行转换操作,新生成的Stream只包含转换生成的元素。其实就是类似一对一映射处理。
flatMap:和map类似,不同的是其每个元素转换得到的是Stream对象,会把子Stream中的元素压缩到父集合中;正如其名,将几个stream合并到一起,扁平化管理。