Lesson 10 of 10

Lists and maps

Goal

Counting and grouping with ArrayList and HashMap

01

Explanation

An array has a fixed length, but an ArrayList is a list that grows and shrinks. You create one with List<String> loot = new ArrayList<>();, then use loot.add("sword") to add, loot.get(0) to read, loot.size() to get the count, and loot.contains("bow") to check whether an item is there. What you write between < > is the element type, and only a class name is allowed there, so you write Integer instead of int, and Java converts between the two on its own.

A HashMap is a map that links each key to a value, like Map<String, Integer> counts = new HashMap<>();. put(k, v) stores the value or replaces it, get(k) returns the value, or null if the key isn't there, and getOrDefault(k, 0) returns zero instead of null. Counting is built on that: counts.put(w, counts.getOrDefault(w, 0) + 1). For grouping, use computeIfAbsent(key, k -> new ArrayList<>()), which returns the key's list and creates it the first time.

You walk through the key-value pairs with for (Map.Entry<String, Integer> e : counts.entrySet()) and take e.getKey() and e.getValue() from each pair. Keep in mind that a HashMap guarantees no order at all, neither insertion order nor alphabetical order, so if you want the keys sorted, copy them into new TreeMap<>(counts).

02

Your task

Write countWords(text) to return how many times each word appears, converting words to lower case and ignoring extra spaces, and returning an empty map for empty text. Write byLength(words) to group the words into lists by length, in the order they appear. Then write mostCommon(counts) to return the most frequent word, or "" if the map is empty. Finally, print each word in counts from main with its count on its own line in the form gg: 3, sorted alphabetically.

Checks

5 checks
  1. countWords counts every word
  2. countWords lowercases words and ignores extra spaces
  3. byLength groups words by length in the order they appear
  4. mostCommon returns the most frequent word, and "" for an empty map
  5. The words and their counts were printed in alphabetical order
03

Hints

0/3
Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.

Main.java
OutputJava 13 (Judge0)

Compiling and running your code on the server.

–/5

Compiling and running your code on the server.

5 checks listed under “Your task”.

Track lessons0 of 10 done

Java is the language behind Android apps and large systems. Everything in it lives inside a class, and you state every variable's type explicitly.

Beginner level, 10 lessons, 2 hours in total.