Memra

Map: HashMap, LinkedHashMap, TreeMap and key operations

◈ 4 cards

Storing and retrieving key-value pairs — including the modern putIfAbsent, computeIfAbsent, and merge methods.

Map basics

A Map<K,V> maps unique keys to values. The key must be unique; values may repeat.

Map<String, Integer> pop = new HashMap<>();
pop.put("Tokyo",   14000000);
pop.put("London",  9000000);
pop.put("Tokyo",   14500000);  // replaces previous value
System.out.println(pop.get("London"));            // 9000000
System.out.println(pop.getOrDefault("Paris", 0)); // 0
System.out.println(pop.containsKey("Tokyo"));     // true

Iterating a Map:

// Three views:
for (String key : pop.keySet())           { ... }
for (Integer val : pop.values())          { ... }
for (Map.Entry<String,Integer> e : pop.entrySet()) {
    System.out.println(e.getKey() + " = " + e.getValue());
}

Modern merge methods:

// putIfAbsent: only inserts if the key is missing
pop.putIfAbsent("Paris", 2200000);

// computeIfAbsent: compute and insert only if missing
Map<String, List<String>> groups = new HashMap<>();
groups.computeIfAbsent("admin", k -> new ArrayList<>()).add("alice");

// merge: combine existing value with new one, or insert if absent
Map<String, Integer> wordCount = new HashMap<>();
wordCount.merge("java", 1, Integer::sum); // 1
wordCount.merge("java", 1, Integer::sum); // 2

Three implementations:

ClassOrderOperations
HashMapNoneO(1) average get/put
LinkedHashMapInsertion orderO(1) average
TreeMapNatural/Comparator sortO(log n)

TreeMap also implements NavigableMap giving floorKey, ceilingKey, headMap, tailMap.

call on popresultput("Tokyo", 14500000)replaces 14000000get("London")9000000getOrDefault("Paris", 0)0 — nothing insertedputIfAbsent("Paris", 2200000)inserts — Paris was absentcontainsKey("Tokyo")truepop maps a city name to its population.
Only two of these five change the map. get and getOrDefault never insert — getOrDefault hands back 0 for Paris and leaves the map untouched, which is why putIfAbsent still has work to do on the next line.
NORMAL ~/memra/learn/java-from-zero/map-operations utf-8 LF