一、异同点
<R> Stream<R> map(Function<? super T, ? extends R> mapper);
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
他们的相同点是接收的入参都是一个function。
不同点这个入参function的返回不同。map返回一个对象,flatmap返回一个stream。
这就使得map是一对一的处理,得到的stream中元素的数量和原始数量一致,而flatmap返回stream这就使得flatmap可以具备一对多的处理能力。最后这个function的stream汇聚到一个stream中,数量可以多于原始元素的数量。
二、示例
public static void main(String[] args) { List<String> list = Arrays.asList("a1","a2","a3"); list.stream().map(s->s+"test").forEach(System.out::println);//一对一的处理,在每个字符串后面加上test输出 list.stream().flatMap(s -> Stream.of(s.split(""))).forEach(System.out::println);//一对多的处理,把每个字符串拆成一个个字符,输出,这点map就无法做到。 }
输出:
a1test a2test a3test a 1 a 2 a 3
转自:https://www.cnblogs.com/liuboyuan/p/12098370.html
- map
把
数组流
中的每一个值,使用所提供的函数执行一遍,一一对应。得到元素个数相同的数组流
。
- flatMap
flat是扁平的意思。它把数组流
中的每一个值,使用所提供的函数执行一遍,一一对应。得到元素相同的数组流
。只不过,里面的元素也是一个子数组流
。把这些子数组合并成一个数组以后,元素个数大概率会和原数组流
的个数不同。
转自:https://georgedage.blog.csdn.net/article/details/103058301