Home › Learn › Java › Arrays and lists

HashMap

Lesson 20 of 40. Look values up by key instead of by position.

A map stores pairs: Map<String, Integer> stock = new HashMap<>(); maps strings to integers. stock.put("pens", 12) stores, stock.get("pens") reads (and gives null for a missing key, so getOrDefault("pens", 0) is often what you want), stock.containsKey("pens") asks, stock.remove("pens") deletes, stock.size() counts. stock.keySet() and stock.entrySet() let a for-each loop visit the keys or the pairs.

Counting things is the classic map: for each item, counts.put(item, counts.getOrDefault(item, 0) + 1). A HashMap keeps no particular order; when order matters, TreeMap sorts by key and LinkedHashMap keeps insertion order.

Map<String, Integer> counts = new HashMap<>();
for (String w : words) {
    counts.put(w, counts.getOrDefault(w, 0) + 1);
}
System.out.println(counts.get("the"));

Your task

Write static Map<String, Integer> wordCounts(List<String> words) returning how often each word appears, and static String mostCommon(Map<String, Integer> counts) returning the key with the highest count (assume the counts are distinct and the map is not empty).

Hint 1

counts.put(w, counts.getOrDefault(w, 0) + 1) for each word.

Hint 2

mostCommon: keep the best key and count; for (String key : counts.keySet()) if (counts.get(key) > bestCount) { best = key; bestCount = counts.get(key); } starting bestCount at -1.

Show the solution
import java.util.*;

public class Main {
    static Map<String, Integer> wordCounts(List<String> words) {
        Map<String, Integer> counts = new HashMap<>();
        for (String w : words) {
            counts.put(w, counts.getOrDefault(w, 0) + 1);
        }
        return counts;
    }

    static String mostCommon(Map<String, Integer> counts) {
        String best = "";
        int bestCount = -1;
        for (String key : counts.keySet()) {
            if (counts.get(key) > bestCount) {
                best = key;
                bestCount = counts.get(key);
            }
        }
        return best;
    }

    public static void main(String[] args) {
        Map<String, Integer> counts = wordCounts(List.of("a", "b", "a"));
        System.out.println(counts + " " + mostCommon(counts));
    }
}

    Compiles with OpenJDK javac and TeaVM, both compiled to WebAssembly (7 MB download the first time, then cached), and runs in this tab; nothing is sent anywhere.