java8中map和flatmap的理解_Java 8中的map和flatMap方法有什么区别?

映射: – 此方法将一个Function作为参数,并返回一个新的stream,该stream包含通过将传递的函数应用于stream的所有元素而生成的结果。

让我们想象一下,我有一个整数值列表(1,2,3,4,5)和一个函数接口,其逻辑是通过整数的平方。 (e – > e * e)。

List intList = Arrays.asList(1, 2, 3, 4, 5); List newList = intList.stream().map( e -> e * e ).collect(Collectors.toList()); System.out.println(newList);

输出: –

[1, 4, 9, 16, 25]

如您所见,输出是一个新的stream,其值是inputstream的值的平方。

[1, 2, 3, 4, 5] -> apply e -> e * e -> [ 1*1, 2*2, 3*3, 4*4, 5*5 ] -> [1, 4, 9, 16, 25 ]

FlatMap: – 此方法接受一个Function作为参数,该函数接受一个参数T作为input参数,并返回一个参数R的stream作为返回值。 当这个函数应用于这个stream的每个元素时,它会产生一个新的值stream。 所有这些由每个元素生成的新stream的元素都被复制到一个新的stream中,这将是这个方法的返回值。

让我们来看看,我有一个学生对象列表,每个学生可以select多个主题。

List studentList = new ArrayList(); studentList.add(new Student("Robert","5st grade", Arrays.asList(new String[]{"history","math","geography"}))); studentList.add(new Student("Martin","8st grade", Arrays.asList(new String[]{"economics","biology"}))); studentList.add(new Student("Robert","9st grade", Arrays.asList(new String[]{"science","math"}))); Set courses = studentList.stream().flatMap( e -> e.getCourse().stream()).collect(Collectors.toSet()); System.out.println(courses);

输出: –

[economics, biology, geography, science, history, math]

如你所见,output是一个新的stream,其值是inputstream的每个元素返回的stream的所有元素的集合。

[S1,S2,S3] – > [{“history”,“math”,“geography”},{“economics”,“biology”},{“science”,“math”}] > [经济,生物,地理,科学,历史,math]

你可能感兴趣的:(java8中map和flatmap的理解_Java 8中的map和flatMap方法有什么区别?)