Java 8 - How to count words in a text file in Java using NIO and Streams API
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
Contents of the input Text file "WordCount.txt" (Total: 30 words)
This is the first paragraph. This is the second line. This is the third line. This is the second paragraph. This is the fifth line. This is the sixth line.
Java 8 Streams code to count the number of words in a text file
package com.javabrahman.java8;
import java.io.IOException;
import java.nio.charset.Charset;
import java.nio.file.Files;
import java.nio.file.Path;
import java.nio.file.Paths;
import java.util.Arrays;
import java.util.stream.Stream;
public class FileWordCount {
public static void main(String args[]) {
long wordCount = 0;
Path textFilePath = Paths.get("C:\\JavaBrahman\\WordCount.txt");
try {
Stream<String> fileLines = Files.lines(textFilePath, Charset.defaultCharset());
wordCount = fileLines.flatMap(line -> Arrays.stream(line.split(" "))).count();
} catch (IOException ioException) {
ioException.printStackTrace();
}
System.out.println("Number of words in WordCount.txt: "+ wordCount);
}
}
Number of words in WordCount.txt: 30
- The
get()
method of NIO API'sjava.nio.file.Paths
class is used to get thejava.nio.file.Path
handle, namedtextFilePath
, to the text file"WordCount.txt"
. The full URI to the text file is passed as input to the method. lines()
method ofjava.nio.file.Files
class is invoked with thePath
variabletextFilePath
and the deault character set usingCharset.defaultCharset()
method. ThedefaultCharset()
method returns the default character set of the JVM on which the code is running.Files.lines()
method returns aStream of Strings
, orStream<String>
, with eachString
element of theStream
representing a line in the file.- Next we map each line of the text file, of type
String
, to its equivalent flattenedStream
of 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 aString array
.Arrays.stream()
method then creates aStream
of Strings, orStream<String>
for every line.- We now effectively have a
Stream
ofStream<String>
elements orStream<Stream<String>>
. We then applyStream.flatMap()
method to flattenClick to understand the working of flatMap() method theStream<Stream<String>>
into oneStream<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 theStream<String>
which is the total number of words in the text file or 30, as is the output.
Java 8 Streams API tutorials on JavaBrahman
Streams API - Introduction & BasicsClick to Read tutorial on Streams API Basics Understanding Stream Operations | Intermediate and Terminal OperationsClick to Read Tutorial on Stream Operations Overview Mapping with Streams using map and flatMap methodsClick to Read how Mapping with Java8 Streams works Filtering and Slicing with Streams using filter,distinct,limit,skip methodsClick to Read how Filtering and Slicing with Java8 Streams works Matching with Streams using allMatch,anyMatch,noneMatch methodsClick to Read tutorial on matching with Streams API Stream API's findFirst,findAny methods' tutorialClick to Read tutorial on findFirst() and findAny() methods of Streams API 'Peeking' into a running Stream with Stream.peek() methodClick to Read tutorial on Stream.peek() method Creating Infinite Streams with iterate\generate methodsClick to Read tutorial on Creating Infinite Streams Reducing Streams using Streams.reduce methodClick to Read tutorial on Reducing Streams
Streams API - Introduction & BasicsClick to Read tutorial on Streams API Basics Understanding Stream Operations | Intermediate and Terminal OperationsClick to Read Tutorial on Stream Operations Overview Mapping with Streams using map and flatMap methodsClick to Read how Mapping with Java8 Streams works Filtering and Slicing with Streams using filter,distinct,limit,skip methodsClick to Read how Filtering and Slicing with Java8 Streams works Matching with Streams using allMatch,anyMatch,noneMatch methodsClick to Read tutorial on matching with Streams API Stream API's findFirst,findAny methods' tutorialClick to Read tutorial on findFirst() and findAny() methods of Streams API 'Peeking' into a running Stream with Stream.peek() methodClick to Read tutorial on Stream.peek() method Creating Infinite Streams with iterate\generate methodsClick to Read tutorial on Creating Infinite Streams Reducing Streams using Streams.reduce methodClick to Read tutorial on Reducing Streams