Given a file, we can transform it into a stream of strings using, e.g.,
Stream lines = Files.lines(Paths.get(\"input.txt\"))
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();
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());
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);