Task 1 of 7 · 0 solved · 7 to go0%
You can read the problem, but answers are checked only for signed-in students. Sign in to answer →

10.4 Patterns — analyzing a frequency map

Lesson

From counts to answers

You already know how to build a frequency map (word → count). The next step is to analyze it: loop over the map and compute something. A common question is "what is the highest count?" — the frequency of the most common element. Because you only compare counts, the answer does not depend on the map's order.


Worked example

String[] words = {"a", "b", "a", "c", "a", "b"};
Map<String, Integer> counts = new HashMap<String, Integer>();
for (int i = 0; i < words.length; i++) {
    counts.put(words[i], counts.getOrDefault(words[i], 0) + 1);
}
int max = 0;
for (String key : counts.keySet()) {
    if (counts.get(key) > max) {
        max = counts.get(key);
    }
}
System.out.println(max);            // 3 — "a" appears three times
System.out.println(counts.size());  // 3 — three distinct words

▶ Try it: run this — build the counts, then scan them for the largest.



The highest value in a frequency map is...


To find the largest count, you...


Type exactly what this program prints.

import java.util.HashMap;
import java.util.Map;
public class Main { public static void main(String[] x){
    String[] w = {"p", "q", "p", "p", "q"};
    Map<String, Integer> c = new HashMap<String, Integer>();
    for (int i = 0; i < w.length; i++) { c.put(w[i], c.getOrDefault(w[i], 0) + 1); }
    int m = 0;
    for (String k : c.keySet()) { if (c.get(k) > m) { m = c.get(k); } }
    System.out.println(m);
}}

Why is the largest count independent of the map's order?


True or false?