如何从 System.in / System.console() 构建 Java 8 流?

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/29154405/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-11-02 14:45:47  来源:igfitidea点击:

How to build a Java 8 stream from System.in / System.console()?

javajava-8java-stream

提问by Georgy Ivanov

Given a file, we can transform it into a stream of strings using, e.g.,

给定一个文件,我们可以使用例如,将其转换为字符串流

Stream<String> lines = Files.lines(Paths.get("input.txt"))

Can we build a stream of lines from the standard input in a similar way?

我们可以以类似的方式从标准输入构建一个行流吗?

回答by Georgy Ivanov

A compilation of kocko's answer and Holger's comment:

kocko 的回答和 Holger 的评论的汇编:

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
Stream<String> stream = in.lines().limit(numberOfLinesToBeRead);

回答by Adrian

you can use just Scannerin combination with Stream::generate:

您可以仅ScannerStream::generate以下组合使用:

Scanner in = new Scanner(System.in);
List<String> input = Stream.generate(in::next)
                           .limit(numberOfLinesToBeRead)
                           .collect(Collectors.toList());

or (to avoid NoSuchElementExceptionif user terminates before limit is reached):

或(避免NoSuchElementException用户在达到限制之前终止):

Iterable<String> it = () -> new Scanner(System.in);

List<String> input = StreamSupport.stream(it.spliterator(), false)
            .limit(numberOfLinesToBeRead)
            .collect(Collectors.toList());

回答by Konstantin Yovkov

Usually the standard input is read line by line, so what you can do is store all the read line into a collection, and then create a Streamthat operates on it.

通常标准输入是逐行读取的,所以你可以做的就是将所有读取的行存储到一个集合中,然后创建一个对其Stream进行操作的集合。

For example:

例如:

List<String> allReadLines = new ArrayList<String>();

BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
String s;
while ((s = in.readLine()) != null && s.length() != 0) {
    allReadLines.add(s);
}

Stream<String> stream = allReadLines.stream();