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]

 

posted @ 2022-12-28 10:48  原子切割员  阅读(176)  评论(0编辑  收藏  举报