java stream map和 flatmap区别
区别:
map mapper返回R,flatMap mapper返回Stream<R>
官网解释
1,<R> Stream<R> flatMap(Function<? super T,? extends Stream<? extends R>> mapper)
Returns a stream consisting of the results of replacing each element of this stream with the contents of a mapped stream produced by applying the provided mapping function to each element.
2,<R> Stream<R> map(Function<? super T,? extends R> mapper)
Returns a stream consisting of the results of applying the given function to the elements of this stream.
map(Function f)
接收一个函数作为参数,该函数会被应用到每个元素上,并将其映射成一个新的元素,返回的数据还是一个流。
flatMap(Function f)
接收一个函数作为参数,将流中的每个值都换成另一个流,然后把所有流连接成一个流。
示例代码
import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.stream.Collectors;
import java.util.stream.Stream;
public class MapFlatMap {
public static void main(String[] args) {
List<String> list1 = new ArrayList<>();
list1.add("A");
list1.add("B");
List<String> list2 = new ArrayList<>();
list2.add("C");
list2.add("D");
List<List<String>> list = new ArrayList<>();
list.add(list1);
list.add(list2);
System.out.println("----------对比举例------------");
Stream stream1 = list.stream().map(i-> {
List<String> listT = new ArrayList<>();
i.stream().forEach(j->listT.add("map1>" + j));
return listT;
});
stream1.forEach(System.out::println);
System.out.println();
Stream stream2 = list.stream().flatMap(i->i.stream().map(j->"flatMap2>" + j));
stream2.forEach(System.out::println);
System.out.println("-----------单词合并-----------");
List<String> words = Arrays.asList("hello c++", "hello java", "hello python");
List<String> result = words.stream()
.map(word -> word.split(" ")) // 将单词按照空格切合,返回Stream<String[]>类型的数据
.flatMap(Arrays::stream) // 将Stream<String[]>转换为Stream<String>
.distinct() // 去重
.collect(Collectors.toList());
System.out.println(result);
}
}
输出:
----------对比举例------------
[map1>A, map1>B]
[map1>C, map1>D]
flatMap2>A
flatMap2>B
flatMap2>C
flatMap2>D
-----------单词合并-----------
[hello, c++, java, python]
【推荐】国内首个AI IDE,深度理解中文开发场景,立即下载体验Trae
【推荐】编程新体验,更懂你的AI,立即体验豆包MarsCode编程助手
【推荐】抖音旗下AI助手豆包,你的智能百科全书,全免费不限次数
【推荐】轻量又高性能的 SSH 工具 IShell:AI 加持,快人一步
· TypeScript + Deepseek 打造卜卦网站:技术与玄学的结合
· Manus的开源复刻OpenManus初探
· AI 智能体引爆开源社区「GitHub 热点速览」
· 从HTTP原因短语缺失研究HTTP/2和HTTP/3的设计差异
· 三行代码完成国际化适配,妙~啊~