以前有点搞不懂这两个概念,今天在scala里面看到flatMap是等于map+flatten,把它扁平化的感觉。
就想用Java试一下,确实是降低维度,把它打平的感觉。
官方的一个解释:
map:Returns a stream consisting of the results of applying the given function to the elements of this stream.
返回一个流,包含给定函数应用在流中每一个元素后的结果
flatmap: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.
返回一个流,包含将此流中的每个元素替换为通过给定函数映射应用于每个元素而生成的映射流的内容
来一段代码瞅瞅,造一下数据
List<List<String>> res = new ArrayList<>();
List<String> list = new ArrayList<>();
for (int i = 1; i < 4; i++) {
list.add(i + "");
}
List<String> list2 = new ArrayList<>();
for (int i = 1; i < 5; i++) {
list2.add(i + "");
}
res.add(list);
res.add(list2);
List<Stream<String>> collect1 = res.stream().map((li -> li.stream().map(s -> s + "处理"))).collect(Collectors.toList());
List<String> collect2 = res.stream().flatMap(li -> li.stream().map(s -> s + "处理")).collect(Collectors.toList());
看结果:
用Debug设置断点
发现:
collect1有两层了,而collect2只有一层了,数据都在这一层下面。
用了flatMap确实降低了维度。只有一层了!觉得通俗易懂的给点个赞呗!