word_freq.java in Java
The word-count CLI in Java: read a file, tally a map, print a top ten.
// word_freq: count word frequencies in a file, print the top ten
import java.nio.file.Files;
import java.nio.file.Path;
import java.util.HashMap;
import java.util.Map;
class WordFreq {
public static void main(String[] args) throws Exception {
if (args.length != 1) {
System.err.println("usage: word_freq <file>");
System.exit(1);
}
var counts = new HashMap<String, Integer>();
for (var line : Files.readAllLines(Path.of(args[0]))) {
for (var word : line.toLowerCase().split("[^a-z']+")) {
if (!word.isEmpty()) {
counts.merge(word, 1, Integer::sum);
}
}
}
System.out.println(counts.size() + " distinct words");
counts.entrySet().stream()
.sorted(Map.Entry.<String, Integer>comparingByValue()
.reversed())
.limit(10)
.forEach(e -> System.out.printf("%5d %s%n",
e.getValue(), e.getKey()));
}
}
How it works
argscarries the command line; bad usage exits with code 1.mergewithInteger::summakes the tally one line.- A stream sorts the entries by count and formats the report.
Keywords and builtins used here
WordFreqclassforifmainnewpublicstaticthrowsvarvoid
The run, in numbers
- Lines
- 31
- Characters to type
- 795
- Tokens
- 221
- Three-star pace
- 90 tpm
At the three-star pace of 90 tokens a minute, this run takes about 147 seconds.
Step 1 of 2 in Encore, step 28 of 29 in Language basics.