Java Tutorial · Collections · Lesson 26 of 37

Java HashMap

Store key-value pairs, count things and iterate over entries.

HashMap

A HashMap maps unique keys to values with fast lookups:

Example 1
import java.util.Map;
import java.util.TreeMap;

public class Main {
    public static void main(String[] args) {
        Map<String, Integer> stock = new TreeMap<>();
        stock.put("apples", 5);
        stock.put("pears", 2);
        stock.put("apples", 7);          // replaces the old value
        System.out.println(stock.get("apples") + " " + stock.get("plums"));
        System.out.println(stock.getOrDefault("plums", 0));
        System.out.println(stock.containsKey("pears") + " " + stock.size());
        for (Map.Entry<String, Integer> e : stock.entrySet()) {
            System.out.println(e.getKey() + " = " + e.getValue());
        }
        stock.remove("pears");
        System.out.println(stock);
    }
}

Output

7 null
0
true 2
apples = 7
pears = 2
{apples=7}

Run this on your computer — see “Get Started” for setup.

Counting and grouping

getOrDefault() and merge() make counting easy; computeIfAbsent() builds groups:

Example 2
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 hat and the bat";
        Map<String, Integer> counts = new TreeMap<>();
        for (String word : text.split(" ")) {
            counts.merge(word, 1, Integer::sum);
        }
        System.out.println(counts);
        Map<Integer, List<String>> byLength = new TreeMap<>();
        for (String word : List.of("go", "java", "c", "rust", "js")) {
            byLength.computeIfAbsent(word.length(), k -> new ArrayList<>()).add(word);
        }
        System.out.println(byLength);
    }
}

Output

{and=2, bat=1, cat=1, hat=1, the=3}
{1=[c], 2=[go, js], 4=[java, rust]}

Run this on your computer — see “Get Started” for setup.

HashMap has no guaranteed order. Use LinkedHashMap to keep insertion order, or TreeMap to keep keys sorted.

Hash maps are the #1 tool in coding interviews — try Two Sum and Group Anagrams.

Test yourself

Which Map implementation keeps its keys sorted?

  1. HashMap
  2. LinkedHashMap
  3. TreeMap
  4. EnumMap
Show answer

Answer: TreeMap

Practice next