This quick code tip shows how to count number of words in a text file in Java 8 using the Streams API along with the NIO API. Do take a note of how the file contents are read and the words counted using a single line of pipelined instructions with the Java 8 Streams API.
Contents of the input Text file “WordCount.txt” (Total: 30 words)OUTPUT of the above code Explanation of the code
get()method of NIO API’s
java.nio.file.Pathsclass is used to get the
textFilePath, to the text file
"WordCount.txt". The full URI to the text file is passed as input to the method.
java.nio.file.Filesclass is invoked with the
textFilePathand the deault character set using
defaultCharset()method returns the default character set of the JVM on which the code is running.
Files.lines()method returns a
Stream of Strings, or
Stream<String>, with each
Stringelement of the
Streamrepresenting a line in the file.
- Next we map each line of the text file, of type
String, to its equivalent flattened
Streamof word strings. This is done in 3 steps-
String.split()method is specified using a lambda expressionClick to read Java 8 lambda expressions tutorial to separate the words in each line and store them in a
Arrays.stream()method then creates a
Streamof Strings, or
Stream<String>for every line.
- We now effectively have a
Stream<Stream<String>>. We then apply
Stream.flatMap()method to flattenClick to understand the working of flatMap() method the
Stream<String>. The elements of this flattened stream are all the words in the text file.
- The flattened stream is then pipelinedClick to understand the concept of pipelining to
Stream.count()method is used to count the number of elements in the
Stream<String>which is the total number of words in the text file or 30, as is the output.