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

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

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

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

我们能否以类似的方式从标准输入构建行流?

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

例如:

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();

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

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

您可以仅将 ScannerStream::generate 结合使用:

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

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

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

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