I am reading bunch of integers separated by space or newlines from the standard in using Scanner(System.in)
.
Is there any faster way of doing this in Java?
Using Reader Class It uses inputDataStream to read through the stream of data and uses read() method and nextInt() methods for taking inputs. It is the fastest method in java for input.
Read Input by Using System.in in Java Using the System.in in a Java code is easy; pass the class in the Scanner constructor and use the nextLine() method. This method reads and returns a string.
BufferReader is faster than Scanner as it only reads a character stream. Scanner has methods like nextInt(), nextShort() etc. BufferReader has methods like parseInt(), parseShort() etc. Scanner has method nextLine() to read a line.
in is a static data member in the system class of type input stream class. Input stream class belongs java.io package. read byte[] is available in the input stream class. System indicates the current computer system. in indicates standard input device.
Is there any faster way of doing this in Java?
Yes. Scanner is fairly slow (at least according to my experience).
If you don't need to validate the input, I suggest you just wrap the stream in a BufferedInputStream and use something like String.split
/ Integer.parseInt
.
A small comparison:
Reading 17 megabytes (4233600 numbers) using this code
Scanner scanner = new Scanner(System.in); while (scanner.hasNext()) sum += scanner.nextInt();
took on my machine 3.3 seconds. while this snippet
BufferedReader bi = new BufferedReader(new InputStreamReader(System.in)); String line; while ((line = bi.readLine()) != null) for (String numStr: line.split("\\s")) sum += Integer.parseInt(numStr);
took 0.7 seconds.
By messing up the code further (iterating over line
with String.indexOf
/ String.substring
) you can get it down to about 0.1 seconds quite easily, but I think I've answered your question and I don't want to turn this into some code golf.
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