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

2022-09-02 03:30:23

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

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

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


答案 1

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

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

答案 2

您可以与以下各项结合使用: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());

推荐