Web / Apache Commons Collections Interview questions
How can you optimize repeated multi-field lookups using MultiKeyMap?
A common but inefficient pattern for combining two lookup keys is nesting maps: Map<K1, Map<K2, V>>. Every lookup then costs two hash operations, plus a null-check on the intermediate map before you can even attempt the second lookup - and inserting a brand-new K1 means remembering to create the inner map first.
// nested-map approach - two lookups, extra null-handling Map<String, Map<String, Double>> distances = new HashMap<>(); distances.computeIfAbsent("NYC", k -> new HashMap<>()).put("LA", 2451.0); Double d1 = distances.getOrDefault("NYC", Map.of()).get("LA"); // MultiKeyMap approach - single combined lookup MultiKeyMap<String, Double> multi = new MultiKeyMap<>(); multi.put("NYC", "LA", 2451.0); Double d2 = multi.get("NYC", "LA");
MultiKeyMap combines all the key components into one MultiKey object whose hashcode blends the components together, so a lookup across two to five key parts is a single O(1)-average hash operation against one backing table - no intermediate map, no null-checking layer, and no risk of forgetting to initialize an inner map before an insert.
The optimization is most worthwhile when the key is naturally a small fixed tuple (like a coordinate pair, a (region, category) combination, or a (year, month) key) and lookups happen frequently enough that the extra hash traversal and null-handling of nested maps would add measurable overhead.
More Related questions...