Reading history

Java HashMap: put, get, Iteration and Word Count

5 min read 0 views

Learn Java HashMap: put, get, getOrDefault, containsKey, looping over entries, merge and computeIfAbsent, and HashMap vs LinkedHashMap vs TreeMap.

A HashMap stores data as key-value pairs, like a dictionary where each word (key) has one meaning (value). Looking up a value by its key takes about the same time whether the map holds ten entries or ten million, which makes maps ideal for counting, caching and indexing. This lesson covers the core operations, iteration, sorted maps and useful helpers such as getOrDefault and merge.

In this lesson you will learn

  • put, get, remove and containsKey
  • What happens with duplicate and missing keys
  • Looping over keys, values and entries
  • HashMap vs LinkedHashMap vs TreeMap
  • Counting and grouping with merge and computeIfAbsent

Basic Operations

import java.util.HashMap;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new HashMap<>();
        stock.put("pen", 40);
        stock.put("notebook", 25);
        stock.put("eraser", 60);
        stock.put("pen", 35);                     // same key: value replaced
        System.out.println("pen: " + stock.get("pen"));
        System.out.println("ruler: " + stock.get("ruler"));
        System.out.println("ruler or 0: " + stock.getOrDefault("ruler", 0));
        System.out.println("has eraser? " + stock.containsKey("eraser"));

        stock.remove("eraser");
        System.out.println("size: " + stock.size());

        // TreeMap keeps keys sorted, HashMap does not promise any order
        Map<String, Integer> sorted = new TreeMap<>(stock);
        for (Map.Entry<String, Integer> e : sorted.entrySet()) {
            System.out.println(e.getKey() + " -> " + e.getValue());
        }
    }
}

Output

pen: 35
ruler: null
ruler or 0: 0
has eraser? true
size: 2
notebook -> 25
pen -> 35
  • Map<String, Integer> means keys are strings and values are integers.
  • Keys are unique. Putting "pen" a second time replaces its value (40 becomes 35); it does not add a second entry.
  • get returns null for a missing key. getOrDefault(key, fallback) avoids null checks.
  • A HashMap does not keep any particular order. A TreeMap keeps keys sorted, so it is used here for predictable printing.
  • entrySet() gives key-value pairs, the most efficient way to loop when you need both. Use keySet() or values() when you need only one side.

Counting and Grouping

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        String text = "the cat and the dog and the bird";

        // Word count with merge()
        Map<String, Integer> counts = new TreeMap<>();
        for (String w : text.split(" ")) {
            counts.merge(w, 1, Integer::sum);
        }
        System.out.println(counts);

        // Group words by length with computeIfAbsent()
        Map<Integer, List<String>> byLength = new TreeMap<>();
        for (String w : counts.keySet()) {
            byLength.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w);
        }
        System.out.println(byLength);

        counts.putIfAbsent("cat", 100);   // key exists: nothing changes
        counts.putIfAbsent("fish", 1);    // key missing: added
        System.out.println("cat=" + counts.get("cat") + ", fish=" + counts.get("fish"));
    }
}

Output

{and=2, bird=1, cat=1, dog=1, the=3}
{3=[and, cat, dog, the], 4=[bird]}
cat=1, fish=1
  • merge(key, 1, Integer::sum) means “put 1 if the key is new, otherwise add 1 to the old value”. It turns word counting into one line.
  • computeIfAbsent(key, k -> new ArrayList<>()) creates the list the first time a key is seen and returns it, so you can call add straight away. This is the standard way to group items.
  • putIfAbsent only writes when the key is missing.

Choosing a Map

TypeOrder of keysget / putNull key
HashMapNo guaranteed orderO(1) averageOne allowed
LinkedHashMapInsertion orderO(1) averageOne allowed
TreeMapSorted by keyO(log n)Not allowed

A HashMap works by turning each key into a number with hashCode() and using it to pick a bucket. For this to work, keys must have consistent equals() and hashCode() methods. String, Integer and records already do. If a key object changes after it is inserted, the map may never find it again, so use immutable keys.

Common Mistakes

  1. Assuming HashMap keeps insertion order; use LinkedHashMap for that.
  2. Unboxing a missing value: int n = map.get("x"); throws NullPointerException if the key is absent.
  3. Using a mutable or custom key without equals and hashCode.
  4. Modifying the map while looping over it with for-each; use entrySet().removeIf(...) instead.

Practice Exercises

Exercise 1. Count how many times each character appears in "banana".

Show answer
Map<Character, Integer> freq = new TreeMap<>();
for (char c : "banana".toCharArray()) {
    freq.merge(c, 1, Integer::sum);
}
System.out.println(freq);   // {a=3, b=1, n=2}

Exercise 2. Given a map of student names to marks, print the names of students with marks of 80 or more.

Show answer
for (Map.Entry<String, Integer> e : marks.entrySet()) {
    if (e.getValue() >= 80) System.out.println(e.getKey());
}

Frequently Asked Questions

Is HashMap thread-safe?

No. If several threads update a map, use ConcurrentHashMap, covered with other tools in Java Multithreading.

What is the difference between HashMap and Hashtable?

Hashtable is an older class whose methods are all synchronized and which rejects null keys and values. New code uses HashMap or ConcurrentHashMap.

Summary

  • A map links unique keys to values; put replaces an existing key’s value.
  • getOrDefault, merge and computeIfAbsent remove most null checks.
  • Pick HashMap for speed, LinkedHashMap for insertion order, TreeMap for sorted keys.
  • Keys need correct equals and hashCode and should not change.

Next: Java HashSet and TreeSet.

Lessons are also marked complete when you click Next.

Leave a Reply

Your email address will not be published. Required fields are marked *