#The collections map
AddedJavaScript gives you three containers: Array, Set and Map (plus plain objects used as maps). Java gives you interfaces that say what a container does, and several implementations of each that differ in speed, ordering and memory. You declare variables with the interface and pick the implementation once, where you create it: List<String> names = new ArrayList<>();. Code that receives names only knows it's a List, so you can swap the implementation without touching it.
| Interface | What it is | Implementations you'll use | Closest in JavaScript |
|---|---|---|---|
List | ordered, indexed, duplicates allowed | ArrayList (the default), LinkedList (rarely) | Array |
Set | no duplicates | HashSet (no order), LinkedHashSet (insertion order), TreeSet (sorted) | Set |
Map | key → value | HashMap (no order), LinkedHashMap (insertion order), TreeMap (sorted keys) | Map |
Queue / Deque | take from the front; Deque adds both ends | ArrayDeque, PriorityQueue (smallest first) | Array with push / shift |
Two differences from JavaScript catch everyone. First, JavaScript's Set and Map always keep insertion order; Java's HashSet and HashMap don't. If you want JavaScript's behaviour, use LinkedHashSet and LinkedHashMap. Second, keys are compared with equals and hashCode, not by reference. A JavaScript Map compares object keys by identity, so two equal-looking arrays are two different keys. A Java HashMap asks the key itself whether it equals another, so List.of(1, 2) finds an entry stored under a different List.of(1, 2). That's why equals and hashCode matter so much in Java (chapter 03), and why records, which generate both, make good keys.
The mental model: the interface is the contract, the implementation is a data structure you chose for its costs. Most of this chapter is about those costs.
record Point(int x, int y) {}
void main() {
List<String> cart = new ArrayList<>(List.of("keyboard", "mouse"));
cart.add("mouse");
IO.println(cart + " size " + cart.size() + ", first " + cart.get(0));
Set<String> unique = new LinkedHashSet<>(cart);
IO.println(unique + " has mouse: " + unique.contains("mouse"));
Map<String, Integer> stock = new HashMap<>();
stock.put("keyboard", 5);
IO.println(stock.get("keyboard") + " " + stock.get("monitor") + " " + stock.getOrDefault("monitor", 0));
Map<Point, String> grid = new HashMap<>();
grid.put(new Point(1, 2), "treasure");
IO.println("point key: " + grid.get(new Point(1, 2)));
Map<List<Integer>, String> byList = new HashMap<>();
byList.put(List.of(1, 2), "pair");
IO.println("list key: " + byList.get(List.of(1, 2)));
}$ java Collections.java
[keyboard, mouse, mouse] size 3, first keyboard
[keyboard, mouse] has mouse: true
5 null 0
point key: treasure
list key: pairconst cart = ["keyboard", "mouse"];
cart.push("mouse");
console.log(cart, "length", cart.length);
const unique = new Set(cart);
console.log(unique, "has mouse:", unique.has("mouse"));
const stock = new Map([["keyboard", 5]]);
console.log(stock.get("keyboard"), stock.get("monitor"), stock.get("monitor") ?? 0);
const grid = new Map();
grid.set({ x: 1, y: 2 }, "treasure");
console.log("point key:", grid.get({ x: 1, y: 2 }));
const byList = new Map();
byList.set([1, 2], "pair");
console.log("list key:", byList.get([1, 2]));$ node collections.mjs
[ 'keyboard', 'mouse', 'mouse' ] length 3
Set(2) { 'keyboard', 'mouse' } has mouse: true
5 undefined 0
point key: undefined
list key: undefined- Lists look the same in both languages: an
ArrayListbuilt fromList.of(…)(so it can grow),addispush,get(0)is[0],size()islength. Printing a Java collection calls itstoString(), which gives[keyboard, mouse, mouse]. - Sets drop the duplicate
mouse.LinkedHashSetkeeps insertion order, like a JavaScriptSet; aHashSetwould also drop it but promise no order. - Maps: a missing key gives
nullin Java andundefinedin JavaScript.getOrDefaultis Java's?? 0. - Object keys are where they differ. Java looks up
new Point(1, 2)and finds the entry stored under a differentPoint(1, 2), because the record'sequalsandhashCodesay they're equal. JavaScript compares object keys by identity, so a new{ x: 1, y: 2 }is a different key and the lookup givesundefined. - Same with lists as keys: Java's
List.equalscompares elements, soList.of(1, 2)finds"pair"; JavaScript's[1, 2]is a new array and finds nothing. In JavaScript you'd use a string key like"1,2"; in Java you use a record or a list.
If you learned Java before 8, you wrote if (map.containsKey(k)) { … } else { … } everywhere. Java 8 added methods that do the check and the update in one call. These four cover nearly every case:
void main() {
var words = List.of("to", "be", "or", "not", "to", "be");
Map<String, Integer> counts = new TreeMap<>();
for (String w : words) {
counts.merge(w, 1, Integer::sum);
}
IO.println("merge: " + counts);
Map<Integer, List<String>> byLength = new TreeMap<>();
for (String w : words) {
byLength.computeIfAbsent(w.length(), k -> new ArrayList<>()).add(w);
}
IO.println("computeIfAbsent: " + byLength);
counts.putIfAbsent("to", 100);
counts.putIfAbsent("question", 0);
IO.println("putIfAbsent: " + counts);
counts.replaceAll((word, n) -> n * 10);
IO.println("replaceAll: " + counts);
}$ java Counts.java
merge: {be=2, not=1, or=1, to=2}
computeIfAbsent: {2=[to, be, or, to, be], 3=[not]}
putIfAbsent: {be=2, not=1, or=1, question=0, to=2}
replaceAll: {be=20, not=10, or=10, question=0, to=20}merge(w, 1, Integer::sum)means "put 1 if the key is new, otherwise combine the old value and 1 withInteger::sum". It's the one-line word count:togoes1 → 2,be1 → 2. ATreeMapkeeps the printout sorted by key.computeIfAbsent(key, k -> new ArrayList<>())returns the existing list for the key, or creates, stores and returns a new one. Then.add(w)adds to it: the standard "group into lists" idiom. Notetoandbeappear twice in the length-2 list, because the input has them twice.putIfAbsentonly writes when the key is missing:tokeeps2, andquestionis added with0.replaceAllrewrites every value from its key and value.- All four arrived in Java 8 (as did
getOrDefault,computeandforEach). Chapter 08'sCollectors.groupingBydoes the grouping with streams.
Vector, Hashtable and Stack are from Java 1.0, before the collections framework (Java 1.2). Every method is synchronized, which costs time and still doesn't make compound actions ("check, then put") safe. You'll see them in old code; in new code use ArrayList, HashMap and ArrayDeque, and for real multi-threaded use the concurrent collections (chapter 09).