Map HashMap TreeMap and LinkedHashMap

Key-Value Pairs

A Map stores keys mapped to values. Keys are unique; putting an existing key replaces its value.

MethodWhat it does
put(k, v)add or replace
get(k)value or null
getOrDefault(k, d)value or default
containsKey(k)is the key present?
putIfAbsent(k, v)add only if missing
merge(k, v, fn)combine with the existing value (great for counting)
remove(k)delete the entry
entrySet(), keySet(), values()views for looping

Counting Words

Example

import java.util.LinkedHashMap;
import java.util.Map;

public class Main {
    public static void main(String[] args) {
        String text = "to be or not to be that is the question to ask";
        Map<String, Integer> freq = new LinkedHashMap<>();
        for (String w : text.split(" ")) {
            freq.merge(w, 1, Integer::sum);       // 1 if new, else old + 1
        }
        System.out.println(freq);

        for (Map.Entry<String, Integer> e : freq.entrySet()) {
            if (e.getValue() > 1) {
                System.out.println(e.getKey() + " -> " + e.getValue());
            }
        }
        System.out.println("'java' count: " + freq.getOrDefault("java", 0));
    }
}

Output

{to=3, be=2, or=1, not=1, that=1, is=1, the=1, question=1, ask=1}
to -> 3
be -> 2
'java' count: 0

HashMap vs LinkedHashMap vs TreeMap

Example

Same data, three iteration orders.

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

public class Main {
    public static void main(String[] args) {
        String[] cities = { "Pune", "Agra", "Surat", "Kochi" };
        int[] pop = { 70, 16, 80, 21 };

        Map<String, Integer> hash = new HashMap<>();
        Map<String, Integer> linked = new LinkedHashMap<>();
        TreeMap<String, Integer> tree = new TreeMap<>();
        for (int i = 0; i < cities.length; i++) {
            hash.put(cities[i], pop[i]);
            linked.put(cities[i], pop[i]);
            tree.put(cities[i], pop[i]);
        }
        System.out.println("HashMap       " + hash);
        System.out.println("LinkedHashMap " + linked);
        System.out.println("TreeMap       " + tree);
        System.out.println("first key: " + tree.firstKey() + ", keys before Pune: " + tree.headMap("Pune").keySet());
    }
}

Output

HashMap       {Kochi=21, Pune=70, Agra=16, Surat=80}
LinkedHashMap {Pune=70, Agra=16, Surat=80, Kochi=21}
TreeMap       {Agra=16, Kochi=21, Pune=70, Surat=80}
first key: Agra, keys before Pune: [Agra, Kochi]
HashMapLinkedHashMapTreeMap
Ordernoneinsertionsorted by key
get/putO(1)O(1)O(log n)
null keyone allowedone allowednot allowed

Grouping with computeIfAbsent

Example

Build a Map<String, List<String>> without null checks.

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[][] students = { { "Asha", "CSE" }, { "Ravi", "ECE" }, { "Meena", "CSE" }, { "John", "MECH" }, { "Zara", "ECE" } };
        Map<String, List<String>> byBranch = new TreeMap<>();
        for (String[] s : students) {
            byBranch.computeIfAbsent(s[1], k -> new ArrayList<>()).add(s[0]);
        }
        byBranch.forEach((branch, names) -> System.out.println(branch + ": " + names));
    }
}

Output

CSE: [Asha, Meena]
ECE: [Ravi, Zara]
MECH: [John]