Sub topic 16
Choosing the Right Collection
You now know the main collection types: ArrayList, LinkedList, HashSet, LinkedHashSet, TreeSet, HashMap, LinkedHashMap, and TreeMap. This chapter shows you how to pick one of them for a task. You can usually decide by answering three or four short questions about your data.
Start with the shape of your data
Your first choice is between the three families. A family here means one of the main interfaces: List, Set, or Map.
- Use a List when order matters and repeats are allowed. A shopping list or a log of events fits here.
- Use a Set when each item should appear only once. Unique email addresses or the tags on a post fit here.
- Use a Map when you look things up by a key. A phone book (name to number) or word counts (word to count) fit here.
After you pick the family, you pick the implementation. An implementation is the actual class, such as ArrayList or HashMap, that does the work behind the interface.
Then decide on order
Each family has a "fast, no promised order" choice, an "insertion order" choice, and a "sorted" choice.
- No promised order:
HashSetandHashMap. They are the fastest in most cases. The order you see when you print them can look random, and it can change as the collection grows. - Insertion order:
LinkedHashSetandLinkedHashMap. Items come back in the order you added them. They cost a little more memory. - Sorted order:
TreeSetandTreeMap. Items are always kept sorted, by natural order or by aComparatoryou supply. They are a bit slower.
A List always keeps the order you put things in, so the order question does not arise for lists. If you want a list sorted, you call sort on it.
Then think about speed
Programmers describe speed with Big-O notation. Big-O is a short way to say how the work grows as the collection gets bigger. You only need three cases here:
- O(1), or constant time: the work stays about the same whether you have 10 items or 10 million.
- O(log n), or logarithmic time: the work grows very slowly. Doubling the size adds only one more step.
- O(n), or linear time: the work grows with the size. Ten times more items means about ten times more work.
| Class | Keeps order? | Duplicates? | Get by index | Contains / lookup | Add |
|---|---|---|---|---|---|
| `ArrayList` | Insertion | Yes | O(1) | O(n) | O(1) at end, O(n) in middle |
| `LinkedList` | Insertion | Yes | O(n) | O(n) | O(1) at ends |
| `HashSet` | No | No | none | O(1) average | O(1) average |
| `LinkedHashSet` | Insertion | No | none | O(1) average | O(1) average |
| `TreeSet` | Sorted | No | none | O(log n) | O(log n) |
| `HashMap` | No | Keys unique | none | O(1) average | O(1) average |
| `LinkedHashMap` | Insertion | Keys unique | none | O(1) average | O(1) average |
| `TreeMap` | Sorted by key | Keys unique | none | O(log n) | O(log n) |
"Average" means the speed holds when your hashCode spreads objects out well. A bad hashCode, such as one that returns the same number for every object, makes hash collections much slower.
Seeing the difference in speed
The most common speed mistake is checking membership in a large List. list.contains(x) checks items one by one, while set.contains(x) jumps almost straight to the right spot. This program measures the gap.
import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;
public class ContainsTiming {
public static void main(String[] args) {
int n = 100_000;
List<Integer> list = new ArrayList<>();
Set<Integer> set = new HashSet<>();
for (int i = 0; i < n; i++) {
list.add(i);
set.add(i);
}
int lookups = 1_000;
long start = System.nanoTime();
int foundInList = 0;
for (int i = 0; i < lookups; i++) {
if (list.contains(n - 1 - i)) foundInList++;
}
long listMs = (System.nanoTime() - start) / 1_000_000;
start = System.nanoTime();
int foundInSet = 0;
for (int i = 0; i < lookups; i++) {
if (set.contains(n - 1 - i)) foundInSet++;
}
long setMs = (System.nanoTime() - start) / 1_000_000;
System.out.println("List found " + foundInList + " in " + listMs + " ms");
System.out.println("Set found " + foundInSet + " in " + setMs + " ms");
}
}Your exact times will vary from machine to machine. The list usually takes tens of milliseconds or more, and the set usually takes close to 0 ms. Both find all 1000 values. The answer is the same and only the speed changes.
One task, three collections
Real programs often use several collections together, each for a different question. Here, a website records visits. You want the full log, the unique visitors in the order they first came, and a count per visitor 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 VisitReport {
public static void main(String[] args) {
String[] visits = {"ben", "ana", "ben", "cara", "ana", "ben"};
List<String> log = new ArrayList<>();
Set<String> firstSeen = new LinkedHashSet<>();
Map<String, Integer> counts = new TreeMap<>();
for (String v : visits) {
log.add(v);
firstSeen.add(v);
counts.merge(v, 1, Integer::sum);
}
System.out.println(log); // [ben, ana, ben, cara, ana, ben]
System.out.println(firstSeen); // [ben, ana, cara]
System.out.println(counts); // {ana=2, ben=3, cara=1}
}
}Each choice answers one question:
- "What happened, in order, with repeats?" is answered by the
ArrayList. - "Who visited, in the order they first came?" is answered by the
LinkedHashSet. - "How many times did each person visit, by name?" is answered by the
TreeMap.
Declare with the interface type
Notice that the variables above are declared as List, Set, and Map, not as ArrayList and so on. This habit is called programming to the interface. If you later need sorted visitors, you change only one word:
Set<String> firstSeen = new TreeSet<>();The rest of the code keeps working because it only uses methods from Set. That makes your first choice cheap to fix if it turns out wrong.
Edge cases that change the choice
Some details are easy to miss and can push you toward a different class.
- null values.
HashSet,HashMap, andArrayListacceptnull.TreeSetandTreeMapwith natural ordering throw aNullPointerExceptionfor anullelement or key, because they cannot comparenull. Collections made withList.of,Set.of, andMap.ofrejectnulltoo. - A comparator decides what counts as a duplicate in a TreeSet. If you sort strings by length, then "kiwi" and "pear" count as equal, and the set keeps only the first one you added.
- LinkedList is rarely the faster list. It is only quick at the two ends. Getting the item at position 5000 means walking through 5000 links. For a queue or stack,
ArrayDequeis usually faster thanLinkedList. - Changing a key after you insert it breaks hash collections. If a field used in
hashCodechanges, the map looks for the key in the wrong place and cannot find it. Use objects that do not change, such asString,Integer, or classes withfinalfields, as keys. - Data that never changes fits
List.of,Set.of, orMap.of. These collections protect the data from accidental edits.
import java.util.Comparator;
import java.util.Set;
import java.util.TreeSet;
public class ComparatorDuplicate {
public static void main(String[] args) {
Set<String> byLength = new TreeSet<>(Comparator.comparing(String::length));
byLength.add("kiwi");
byLength.add("pear"); // same length as kiwi, so treated as a duplicate
byLength.add("fig");
System.out.println(byLength); // [fig, kiwi]
}
}A quick checklist
- Do I look things up by key? If yes, use a Map.
- Must each item be unique? If yes, use a Set. Otherwise, use a List.
- Do I need insertion order, sorted order, or neither? This picks Linked, Tree, or Hash.
- Will I check
containsoften on a large group? If yes, avoid a List. - Will the data never change? If yes, use the
of()factories.
Exercise
You store a student's grades for one test. Two students can get the same grade, and you want to print grades in the order they were entered. Which collection fits, and why?
Show answer
An ArrayList<Integer>. Duplicates are allowed and insertion order is kept. You do not need lookup by key or uniqueness, so a Set or Map would be the wrong family.
Exercise
A spell checker holds 200,000 dictionary words and checks each word of a document against them. The order of the dictionary does not matter. Which collection should hold the dictionary?
Show answer
A HashSet<String>. Each check is a contains call, and HashSet does it in O(1) on average. An ArrayList would scan up to 200,000 words for every word in the document.
Exercise
You need to show product names with their prices, sorted alphabetically by name. What should you use, and what happens if one product name is null?
Show answer
A TreeMap<String, Double> (or TreeMap<String, BigDecimal> for exact money values). It keeps keys sorted. With natural ordering, putting a null key throws a NullPointerException, so you must check for null names before inserting them.
Exercise
Someone writes Set<String> s = new TreeSet<>(Comparator.comparing(String::length)); and adds "cat", "dog", and "horse". What does s contain, and why?
Show answer
[cat, horse]. The comparator says "cat" and "dog" are equal because both have 3 letters, so the TreeSet treats "dog" as a duplicate and does not add it.