Skip to content
Veltoryx Technologies
ProLesson 7.4Intermediate3 min readUpdated 30 October 2026

Map: HashMap, LinkedHashMap and TreeMap

Store key-value pairs, loop over them, count and group with getOrDefault and merge, and pick the right Map implementation.

A Map connects keys to values: user ID → user, word → count, product code → stock. Keys are unique; putting a value for an existing key replaces the old value.

01Everyday Map operations

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

public class MapBasics {
    public static void main(String[] args) {
        Map<String, Integer> stock = new LinkedHashMap<>();
        stock.put("pen", 40);
        stock.put("book", 3);
        stock.put("pen", 35);                       // replaces 40

        System.out.println(stock.get("pen"));
        System.out.println(stock.get("bag"));       // missing key → null
        System.out.println(stock.getOrDefault("bag", 0));
        System.out.println(stock.containsKey("book"));
        stock.putIfAbsent("bag", 10);
        stock.remove("book");
        System.out.println(stock);
    }
}
Expected output
35
null
0
true
{pen=35, bag=10}

Loading the rest of the lesson…