Learn Java · lesson 33 of 61 · about 10 minutes
Project: Word Counter
Find out what the audience thinks: clean the words of their reviews, count them, and print the top three.
What you'll learn
- Split and clean text
- Count with a map
- Sort entries by count
What the audience thinks
After the film, people type what they thought, word by word, until end. The words that come up most say what the audience felt. Each word is cleaned to lower-case letters only, so Fun!, fun, and FUN all count as fun. A map counts the clean words, and the top three are found by copying the map's entries into a list and sorting it by count.
The plan
1. Read every word with a Scanner
2. Clean each word: lowercase, letters only (replaceAll("[^a-z]", ""))
3. Count with merge
4. Copy the entries into a list and sort by count, highest first (ties alphabetically)
The word counter
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.Scanner;
public class Main {
public static void main(String[] args) {
Scanner in = new Scanner(System.in);
HashMap<String, Integer> counts = new HashMap<>();
int total = 0;
while (in.hasNext()) {
String w = in.next().toLowerCase().replaceAll("[^a-z]", "");
if (w.isEmpty()) continue;
counts.merge(w, 1, Integer::sum);
total++;
}
List<Map.Entry<String, Integer>> ranked = new ArrayList<>(counts.entrySet());
ranked.sort((a, b) -> !a.getValue().equals(b.getValue()) ? b.getValue() - a.getValue() : a.getKey().compareTo(b.getKey()));
System.out.println(total + " words, " + counts.size() + " different");
for (int i = 0; i < 3 && i < ranked.size(); i++) {
System.out.println(ranked.get(i).getKey() + ": " + ranked.get(i).getValue());
}
}
}Output
10 words, 6 different
cat: 3
a: 2
the: 2Tip
(a, b) -> ... is a lambda: a small function written inline. sort calls it to compare two entries.
Tip
Compare two Integer counts with equals, not ==. == compares the objects themselves, and for numbers above 127 two equal counts can be different objects.
Now try it yourself
This lesson is free in Codiqo, with 7 questions on what you just read. You can only learn to code by writing code, so it ends with a short program you write yourself, which we run and check straight away.