21

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?

Georgy Ivanov
  • 648
  • 1
  • 11
  • 18
  • See also http://stackoverflow.com/questions/29611661/how-to-make-scanner-strings-into-a-stream-in-java – Vadzim Jul 16 '16 at 19:24

3 Answers3

32

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);
Georgy Ivanov
  • 648
  • 1
  • 11
  • 18
4

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());
Adrian
  • 2,984
  • 15
  • 27
1

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();
Konstantin Yovkov
  • 62,134
  • 8
  • 100
  • 147
  • 5
    If you have a `BufferedReader` there is no need for storing the lines into a `Collection` to [get a `Stream`](http://docs.oracle.com/javase/8/docs/api/java/io/BufferedReader.html#lines--). The bigger problem is that interactive consoles usually don’t have an end-of-file… – Holger Mar 19 '15 at 20:54
  • Nice one. Didn't know this newly introduces method. Thanks, @Holger. :) – Konstantin Yovkov Mar 19 '15 at 20:56
  • Great, BufferedReader.lines will eliminate much of the verbosity in this answer. If the numer of lines to be read is known, then in.limit(numberOfLines) should work here – Georgy Ivanov Mar 19 '15 at 20:59
  • _"interactive consoles usually don’t have an end-of-file…"_ Don't you get an end-of-file when the program terminates? :-P – Lii Mar 20 '15 at 16:37
  • 1
    @Lii: no, a terminated program will not receive an end-of-file as a terminated program can’t receive anything. – Holger Mar 23 '15 at 12:14