Maps In Depth
HashMap is fast and unordered, LinkedHashMap keeps insertion order and TreeMap sorts by key. getOrDefault, putIfAbsent, merge, computeIfAbsent and entrySet make common tasks short.
Example
import java.util.*;
Map<String, Integer> count = new TreeMap<>();
for (String w : "go is go and is go".split(" ")) count.merge(w, 1, Integer::sum);
System.out.println(count);
Map<String, List<Integer>> g = new HashMap<>();
g.computeIfAbsent("a", k -> new ArrayList<>()).add(1);
System.out.println(g + " " + count.getOrDefault("zzz", 0));Result
{and=1, go=3, is=2}
{a=[1]} 0Exercise
Count with merge.
map.(w, 1, Integer::sum)
Quiz Test
These free lessons are for learning. Join a full course for projects, mentor feedback and a verified certificate.