Java8_stream的map和flatmap

假如我们有这样一个需求给定单词列表["Hello","World"],你想要返回列表["H","e","l", "o","W","r","d"]

words.stream()
.map(word -> word.split(""))
.distinct()
.collect(toList());

输出结果为:
[Ljava.lang.String;@33833882
[Ljava.lang.String;@200a570f

但是结果List中是两个List,而不是单个的char.

这个方法的问题在于,传递给map方法的Lambda为每个单词返回了一个String[](String
列表)。因此, map 返回的流实际上是Stream<String[]> 类型的。你真正想要的是用
Stream来表示一个字符流。因此,这是行不通的。

对flatMap的说明:这个在这里的主要作用是对流进行扁平化

List<String> collect1 = Arrays.stream(strings)  -->Stream<String>
                .map(str -> str.split(""))      -->Stream<String[]>
                .flatMap(Arrays::stream)        -->Stream<String>
                .distinct()                     -->Stream<String>
                .collect(Collectors.toList());
        collect1.forEach(System.out::print);
    
输出结果为:HeloWrd
原文地址:https://www.cnblogs.com/AganRun/p/11816040.html