如何将Stream<String[]>转换为Stream<String>?

4

我正在尝试将String[]流转换为String流。

例如:

{ "A", "B", "C" }, {"D, "E" } to "A", "B", "C", "D", "E"

这是我目前的代码:
Files.lines(Paths.get(file)).map(a -> a.split(" "));

Files.lines(path) 返回 Stream[String],我将每个字符串按照空格分割,获得一个包含所有单词的数组(现在是 Stream<String[]>)。

我想将每个单词的数组展平成单独的元素,所以要得到 Stream[String] 而不是 Stream<String[]>

当我使用 flatMap 而不是 map 时,会出现错误: Type mismatch: cannot convert from String[] to Stream<? extends Object>

我认为 flatMap 是用于此目的的?如何最好地完成我想做的事情?


教授提出的问题:

使用流:编写一个按单词长度分类文件中单词的方法:

public static Map<Integer,List<String>> wordsByLength(String file) 
throws IOException {
   // COMPLETE THIS METHOD
}
3个回答

7
<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);
一个Stream#flatMap映射器期望返回一个Stream,但是你返回了一个String[]。为了将String[]转换成Stream<String>,请使用Arrays.stream(a.split(" "))
你的任务完整答案:
public static Map<Integer, List<String>> wordsByLength(String file)
        throws IOException {
    return Files.lines(Paths.get(file))
                .flatMap(a -> Arrays.stream(a.split("\\s+")))
                .collect(Collectors.groupingBy(String::length));
}

3
flatMap函数的参数必须返回一个流(stream),而非数组。
例如:
.flatMap(a -> Arrays.stream(a.split(" ")))

0
你需要使用 .flatMap() 操作:
  • 在正常的.map()操作之后

    Files.lines(Paths.get(file)).map(a -> a.split(" ")).flatMap(Arrays::stream);
    
  • 与正常的map操作结合使用:

    Files.lines(Paths.get(file)).flatMap(a -> Arrays.stream(a.split(" ")));
    

最后你需要的是

public static Map<Integer, List<String>> wordsByLength(String file) throws IOException {
    return Files.lines(Paths.get(file))                      //Stream<String>
            .map(a -> a.split(" "))                          //Stream<String[]>
            .flatMap(Arrays::stream)                         //Stream<String>
            .collect(Collectors.groupingBy(String::length)); //Map<Integer, List<String>>
}

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接