gpt4 book ai didi

java - 您是否必须每次都重新计算 java Stream

转载 作者:行者123 更新时间:2023-12-03 23:08:49 25 4
gpt4 key购买 nike

我写了这个方法:

public static void main(String... args) {
try (var linesStream = Files.lines(Paths.get("C:\\Users\\paul\\Desktop\\java.txt"))) {
Stream<String> words = linesStream.
flatMap(line -> Arrays.stream(line.split(" ")))
.distinct();
System.out.println("There are " + words.count() + " distinct words in this file, here they are:");
words.forEach(System.out::println);
} catch (IOException e) {
System.err.println(e.getMessage());
}
}

我在这里遇到的问题是我对 Stream<String> 这个词进行操作两次。为此,您是否必须显式重建此流,或者是否有一些我可以使用的魔法重置方法?

此外,为了再次重建单词流,我必须重建 linesStream并将其包装到另一个 try/catch block 中......非常冗长。有什么方法可以使这类东西更容易编写?

我想我可以:

    static Stream<String> getStreamFromFile() throws IOException {
return Files.lines(Paths.get("C:\\Users\\paul\\Desktop\\java.txt"));
}

static Stream<String> getDistinctWords(Stream<String> lines) {
return lines
.flatMap(line -> Arrays.stream(line.split(" ")))
.distinct();
}

public static void main(String... args) {
Stream<String> lines1 = null;
Stream<String> lines2 = null;
try {
lines1 = getStreamFromFile();
lines2 = getStreamFromFile();
Stream<String> distinctWords1 = getDistinctWords(lines1);
Stream<String> distinctWords2 = getDistinctWords(lines2);
System.out.println("There are " + distinctWords1.count() + " distinct words in this file, here they are:");
distinctWords2.forEach(System.out::println);
} catch (IOException e) {
System.err.println(e.getMessage());
} finally {
lines1.close();
lines2.close();
}
}

但我只剩下这些了吗?

最佳答案

您不能重复使用流。只需将元素收集到一个集合中,例如List,或调用(有状态)函数输出每个元素并增加计数。

关于java - 您是否必须每次都重新计算 java Stream<T>?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/50554968/

25 4 0