gpt4 book ai didi

java - 如何将 Stream 转换为 Stream

转载 作者:搜寻专家 更新时间:2023-11-01 01:31:14 24 4
gpt4 key购买 nike

我正在尝试将我的 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
}

最佳答案

<R> Stream<R> flatMap(Function<? super T, ? extends Stream<? extends R>> mapper);

A 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));
}

关于java - 如何将 Stream<String[]> 转换为 Stream<String>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/53797858/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com