Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

Tags:

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?

like image 946
Georgy Ivanov Avatar asked Mar 19 '15 20:03

Georgy Ivanov


People also ask

What is System console () in Java?

System. console() returns a java. io. Console instance when it's run from an interactive terminal – on the other hand System.

What is stream () method in Java?

A stream consists of source followed by zero or more intermediate methods combined together (pipelined) and a terminal method to process the objects obtained from the source as per the methods described. Stream is used to compute elements as per the pipelined methods without altering the original value of the object.

What functions for creating streams are in Java 8?

Java 8 offers the possibility to create streams out of three primitive types: int, long and double. As Stream<T> is a generic interface, and there is no way to use primitives as a type parameter with generics, three new special interfaces were created: IntStream, LongStream, DoubleStream.


2 Answers

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);
like image 184
Georgy Ivanov Avatar answered Sep 23 '22 06:09

Georgy Ivanov


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());
like image 31
Adrian Avatar answered Sep 20 '22 06:09

Adrian