Sub topic 16
Choosing the Right Collection
You now know the main collection types. This chapter shows you how to choose one for a task. Most of the time, three questions are enough.
Three Questions to Ask
- Do I look things up by a key? A key is a value you use to find another value, like a name that finds a phone number. If you do, use a
Map. - Can the same element appear twice? If duplicates are allowed, use a
List. If each element must be unique, use aSet. - Does order matter? Some collections keep insertion order, which is the order you added things. Some keep sorted order. Some keep no order you can rely on.
A Quick Reference Table
| Need | Good choice | Why |
|---|---|---|
| A sequence, read by position | `ArrayList` | Fast `get(index)` |
| Unique items, fast "is it there?" | `HashSet` | Fast `contains` |
| Unique items in the order added | `LinkedHashSet` | Remembers insertion order |
| Unique items, always sorted | `TreeSet` | Sorts as you add |
| Key-value lookup | `HashMap` | Fast `get(key)` |
| Key-value pairs, sorted by key | `TreeMap` | Keeps keys sorted |
| Fixed data that must not change | `List.of`, `Set.of`, `Map.of` | Unmodifiable |
Speed in Plain Words
Performance means how much work an operation takes as the collection grows.
ArrayList.containschecks elements one by one. With a million items, it may check a million times.HashSet.containsandHashMap.getuse the hash code to jump close to the right spot. They stay fast as the collection grows.TreeSetandTreeMapare a little slower than hash versions. You pay that cost to keep things sorted.LinkedListis rarely the best choice.ArrayListis usually faster, even for adding items.
A Worked Example
A website logs the pages each visitor opens. We want three things: the full log, the unique pages in the order they were first visited, and a count per page sorted by name.
import java.util.ArrayList;
import java.util.LinkedHashSet;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.TreeMap;
public class ChooseDemo {
public static void main(String[] args) {
List<String> visits = new ArrayList<>(List.of("home", "shop", "home", "cart", "shop"));
System.out.println(visits); // [home, shop, home, cart, shop]
Set<String> uniquePages = new LinkedHashSet<>(visits);
System.out.println(uniquePages); // [home, shop, cart]
Map<String, Integer> counts = new TreeMap<>();
for (String page : visits) {
counts.merge(page, 1, Integer::sum);
}
System.out.println(counts); // {cart=1, home=2, shop=2}
}
}Each need got its own collection. The log allows duplicates, so it is a List. The unique pages keep their first-seen order, so they go in a LinkedHashSet. The counts are sorted by page name, so they go in a TreeMap.
Exercise
You store student ID numbers. Each ID must appear only once, and you often check whether an ID is already registered. Order does not matter. Which collection fits best?
Show answer
A HashSet<Integer>. A Set blocks duplicates, and HashSet answers contains quickly. Order does not matter, so you don't need LinkedHashSet or TreeSet.
Exercise
You need a dictionary that prints words with their definitions in alphabetical order. Which collection should you use?
Show answer
A TreeMap<String, String>. It maps each word (the key) to its definition (the value) and keeps the keys sorted alphabetically.