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?
System. console() returns a java. io. Console instance when it's run from an interactive terminal – on the other hand System.
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.
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.
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);
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());
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With