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

前端 未结 3 2005
眼角桃花
眼角桃花 2021-01-01 15:09

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

Stream lines = Files.lines(Paths.get(\"input.txt\"))

相关标签:
3条回答
  • 2021-01-01 15:34

    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 Stream that operates on it.

    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();
    
    0 讨论(0)
  • 2021-01-01 15:36

    you can use just Scanner in combination with Stream::generate:

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

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

    Iterable<String> it = () -> new Scanner(System.in);
    
    List<String> input = StreamSupport.stream(it.spliterator(), false)
                .limit(numberOfLinesToBeRead)
                .collect(Collectors.toList());
    
    0 讨论(0)
  • 2021-01-01 15:57

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

    BufferedReader in = new BufferedReader(new InputStreamReader(System.in));
    Stream<String> stream = in.lines().limit(numberOfLinesToBeRead);
    
    0 讨论(0)
提交回复
热议问题