Skip to content
Codewilds

Lesson 29 of 34 · Collections & Exceptions

Java HashMap: Key-Value Pairs

medium20 XP3 min read

An ArrayList finds things by position: element 0, element 1, element 2. But often you want to look things up by name — the price of an item, the score of a player, the number of times a word appears. That is what a map does: it stores key → value pairs and finds any value by its key in an instant.

HashMap is the map you will use most in Java. In this lesson you will count words with it — one of the most common jobs in real programs.

Creating a map and adding entries

Map<String, Integer> stock = new HashMap<>();
stock.put("potion", 12);
stock.put("arrow", 250);
stock.put("potion", 15);           // same key: replaces 12

System.out.println(stock.get("potion"));  // 15
System.out.println(stock.size());          // 2

Map<String, Integer> says: keys are Strings, values are Integers (maps hold objects, so int values are boxed into Integer). Every key appears at most once — put with an existing key overwrites the old value. Values may repeat freely. Declaring the variable as the Map interface and creating a HashMap is the usual style.

Reading safely

get returns null when the key is missing. Use the helpers instead of hoping the key exists:

stock.get("shield")                // null
stock.getOrDefault("shield", 0)    // 0
stock.containsKey("arrow")         // true
stock.remove("arrow");             // deletes the entry

Looping over a map

You can loop over the keys, the values, or the entries (key and value together):

Map<String, Integer> scores = new TreeMap<>();
scores.put("Ola", 90);
scores.put("Ari", 75);

for (Map.Entry<String, Integer> entry : scores.entrySet()) {
    System.out.println(entry.getKey() + ": " + entry.getValue());
}
Ari: 75
Ola: 90

Notice TreeMap there. A HashMap does not keep any order — its order depends on hash codes and can change as the map grows, and different Java versions may print the same map differently. Pick the map that matches what you need:

  • HashMap — fastest, order unspecified.
  • TreeMap — keys always sorted.
  • LinkedHashMap — remembers insertion order.

Counting and grouping

Two patterns cover a huge share of real map code. Counting occurrences:

Map<String, Integer> counts = new TreeMap<>();
for (String fruit : new String[] {"apple", "fig", "apple"}) {
    counts.merge(fruit, 1, Integer::sum);   // put 1, or add 1 to the old value
}
System.out.println(counts);   // {apple=2, fig=1}

counts.put(fruit, counts.getOrDefault(fruit, 0) + 1) does the same in a more explicit way.

Grouping values into lists:

Map<Character, List<String>> byLetter = new TreeMap<>();
for (String name : List.of("Ann", "Bob", "Amy")) {
    byLetter.computeIfAbsent(name.charAt(0), k -> new ArrayList<>()).add(name);
}
System.out.println(byLetter);  // {A=[Ann, Amy], B=[Bob]}

computeIfAbsent returns the existing list, or creates (and stores) a new one the first time a key appears.

Keys need equals and hashCode

A HashMap uses hashCode() to find the right bucket and equals() to find the exact key. String, Integer and records already implement both correctly. If you use your own class as a key, override both — otherwise two "equal" objects end up as two different keys.

Common mistakes

  • Unboxing a missing value: int n = map.get("x"); throws a NullPointerException when "x" is not in the map. Use getOrDefault.
  • Relying on HashMap order: printing or looping over a HashMap can give any order. Sort, or use a TreeMap.
  • map.get(key)++ does not compile — the value must be put back: map.put(key, map.get(key) + 1) or merge.

Assignment

Implement three static methods in Main:

  1. wordCounts(String text) returns a Map<String, Integer> with how often each word occurs. Words are separated by one or more spaces and counted case-insensitively (store them in lowercase). Blank text returns an empty map. wordCounts("the cat and the hat") → {the=2, cat=1, and=1, hat=1}
  2. mostFrequent(String text) returns the word with the highest count. On a tie, return the alphabetically first word. Blank text returns "". mostFrequent("bob alice bob alice carol") → "alice"
  3. groupByLength(List<String> words) returns a Map<Integer, List<String>> from word length to the words of that length, in their original order. groupByLength(List.of("cat", "horse", "dog")) → {3=[cat, dog], 5=[horse]}

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.

Maps and dictionaries in other languages

Need a quick reminder? The Java cheat sheet has every topic of Learn Java on one page.

Lesson last updated on .

Write code ↓
Java+20 XP

Lesson 29 is part of the full course. The first 8 lessons are free.

Premium lesson

Unlock the full Learn Java course

  • All 34 lessons, bosses and quizzes — lifetime access
  • One payment of $35, no subscription
  • Finish within 30 days and claim $10.50 (30%) back
Play the 8 free lessons

Want more than one course?

The All-Access Pass unlocks all 8 courses and every new one we release, for $120 once.