AI Hints
Home›Java Tutorial›Sorting with Comparator, Removing While Looping, Practice: Word Counter
Java · Lesson 90 of 120

Practice: Word Counter

Put module ten together.

⏱ 2 min read▶ Video at 1:53:56🎓 Free
Watch this lesson in the Java courseWatch on YouTube ↗Full Java course

Let's put module ten together. Count how often each word appears in a sentence, and find the most common one.

  • Split the text
  • Count each word
  • Find the top one

A word counter

Your turn. Pause the video, and try this. Count how many times each word appears in the sentence. Print the counts in alphabetical order, the number of different words, and the most common word. Here is one solution. Split, with a space, breaks the text into words. A TreeMap keeps the words sorted. Get or default, plus one, counts each word. Then we sort the words by their count, biggest first. The appears three times.

✍️ Exercise: A word counter

Count each word in the sentence (sorted), how many different words, and the most common word.

Show hint

counts.put(w, counts.getOrDefault(w, 0) + 1)

Show solution
Main.javajava
import java.util.*;
public class Main {
    public static void main(String[] args) {
        String text = "the cat sat on the mat the cat ran";
        Map<String, Integer> counts = new TreeMap<>();
        for (String w : text.split(" ")) {
            counts.put(w, counts.getOrDefault(w, 0) + 1);
        }
        System.out.println(counts);
        System.out.println(counts.size() + " different words");
        List<String> top = new ArrayList<>(counts.keySet());
        top.sort(Comparator.comparing(counts::get).reversed());
        System.out.println("Most common: " + top.get(0) + " x" + counts.get(top.get(0)));
    }
}
Output
{cat=2, mat=1, on=1, ran=1, sat=1, the=3}
6 different words
Most common: the x3

What module ten taught

ArrayList is a list that grows. Generics say what a collection holds. Wrapper classes let collections hold numbers. HashMap links keys to values, and HashSet holds unique values. And comparators sort any way you like.

keyvalue
ListArrayList<T>
MapHashMap<K, V>
SetHashSet<T>
SortComparator

Summary

You can now store and organise lots of data. That's the end of module ten. Next module, exceptions and files.

Key takeaways
  • Lists
  • Maps
  • Sets
Next up: What Exceptions Are — when things go wrong