Collections Framework
Junior Always asked 8 min
On this page
The question
What is the difference between a List, a Set and a Map?
30-second answer
A List is an ordered sequence that allows duplicates and access by index. A Set holds no duplicates; HashSet, LinkedHashSet and TreeSet differ in the order they keep. A Map stores key-value pairs with unique keys. List, Set and Queue extend Collection, but Map does not: you loop over its keySet(), values() or entrySet() views instead.
Understand it
The collection interfaces and Map apart
Tap the partsSelect a part to see what it does.
Tap an interface to see what it promises and which classes implement it.
View as text
A hierarchy drawing. Iterable sits at the top. Collection extends it, and List, Set and Queue and Deque branch off Collection, each with its common classes listed beside it. Below a dashed line, Map stands apart with no arrow to Collection and is marked Not a Collection.
Collection: the root interface for a group of elements, with add, remove, contains, size and an iterator. It extends Iterable, so every collection works in a for-each loop.
List: an ordered sequence with positions and duplicates allowed. ArrayList and LinkedList implement it.
Set: no duplicates. HashSet, LinkedHashSet and TreeSet implement it.
Queue and Deque: elements wait to be processed at the head, or at both ends for a Deque. ArrayDeque and PriorityQueue implement them.
Map: key-value pairs with unique keys. HashMap, LinkedHashMap and TreeMap implement it. Map is not a Collection; you loop over its keySet(), values() or entrySet() views.
A hierarchy drawing. Iterable sits at the top. Collection extends it, and List, Set and Queue and Deque branch off Collection, each with its common classes listed beside it. Below a dashed line, Map stands apart with no arrow to Collection and is marked Not a Collection.
Collection: the root interface for a group of elements, with add, remove, contains, size and an iterator. It extends Iterable, so every collection works in a for-each loop.
List: an ordered sequence with positions and duplicates allowed. ArrayList and LinkedList implement it.
Set: no duplicates. HashSet, LinkedHashSet and TreeSet implement it.
Queue and Deque: elements wait to be processed at the head, or at both ends for a Deque. ArrayDeque and PriorityQueue implement them.
Map: key-value pairs with unique keys. HashMap, LinkedHashMap and TreeMap implement it. Map is not a Collection; you loop over its keySet(), values() or entrySet() views.
Takeaway: List, Set and Queue are all Collections and work in a for-each loop; Map stores key-value pairs and is not a Collection.
ArrayList and LinkedList, three operations
CompareArrayList keeps 5 elements in one array: get(2) jumps straight to slot 2, add(x) writes the next free slot, but add(0, x) shifts all 5.
View as text
The same five-element list, a to e, drawn three times, once per operation: get(2), add(0, x) and add(x). Each row names its cost and what happens.
ArrayList keeps 5 elements in one array: get(2) jumps straight to slot 2, add(x) writes the next free slot, but add(0, x) shifts all 5. The rows read: get(2), O(1), jumps straight to slot 2; add(0, x), O(n), shifts all 5 elements right; add(x), O(1) amortized, writes the next free slot.
LinkedList keeps 5 separate linked nodes: add(0, x) and add(x) only relink the head or the tail, but get(2) follows links from the nearer end. The rows read: get(2), O(n), follows links from the nearer end; add(0, x), O(1), relinks the head; add(x), O(1), relinks the tail.
The same five-element list, a to e, drawn three times, once per operation: get(2), add(0, x) and add(x). Each row names its cost and what happens.
ArrayList keeps 5 elements in one array: get(2) jumps straight to slot 2, add(x) writes the next free slot, but add(0, x) shifts all 5. The rows read: get(2), O(1), jumps straight to slot 2; add(0, x), O(n), shifts all 5 elements right; add(x), O(1) amortized, writes the next free slot.
LinkedList keeps 5 separate linked nodes: add(0, x) and add(x) only relink the head or the tail, but get(2) follows links from the nearer end. The rows read: get(2), O(n), follows links from the nearer end; add(0, x), O(1), relinks the head; add(x), O(1), relinks the tail.
Takeaway: ArrayList reaches any index in one step but shifts elements to insert at the front; LinkedList relinks its ends in one step but walks to reach an index.
Which collection fits the need?
ExploreArrayList: the default list: duplicates kept, read by index in O(1), and adding keeps insertion order.
View as text
The elements c, a, b and a are added to the recommended collection, or counted into it when the needs are key-value pairs. The drawing names the collection, shows what it holds afterwards, and marks whether duplicates are kept and whether the order is guaranteed.
Word counts: HashMap: unique keys, lookup by key in O(1) on average, and no guaranteed iteration order. It holds a=2, b=1 and c=1 in no guaranteed order.
Unique visitors: HashSet: duplicates dropped, add and contains in O(1) on average, and no guaranteed order. It holds a, b and c in no guaranteed order.
Sorted tags: TreeSet: duplicates dropped, elements kept sorted at O(log n) per operation. It holds a, b, c.
To-do list: ArrayList: the default list: duplicates kept, read by index in O(1), and adding keeps insertion order. It holds c, a, b, a.
Settings in file order: LinkedHashMap: a HashMap that also iterates in insertion order. It holds c=1, a=2, b=1.
The elements c, a, b and a are added to the recommended collection, or counted into it when the needs are key-value pairs. The drawing names the collection, shows what it holds afterwards, and marks whether duplicates are kept and whether the order is guaranteed.
Word counts: HashMap: unique keys, lookup by key in O(1) on average, and no guaranteed iteration order. It holds a=2, b=1 and c=1 in no guaranteed order.
Unique visitors: HashSet: duplicates dropped, add and contains in O(1) on average, and no guaranteed order. It holds a, b and c in no guaranteed order.
Sorted tags: TreeSet: duplicates dropped, elements kept sorted at O(log n) per operation. It holds a, b, c.
To-do list: ArrayList: the default list: duplicates kept, read by index in O(1), and adding keeps insertion order. It holds c, a, b, a.
Settings in file order: LinkedHashMap: a HashMap that also iterates in insertion order. It holds c=1, a=2, b=1.
Takeaway: Pairs mean a Map, no duplicates means a Set, otherwise a List; the order you need picks Hash, LinkedHash or Tree.
In code
List<String> input = List.of("c", "a", "b", "a");
List<String> list = new ArrayList<>(input); // [c, a, b, a]
Set<String> seen = new LinkedHashSet<>(input); // [c, a, b]
Set<String> sorted = new TreeSet<>(input); // [a, b, c]
Map<String, Integer> counts = new TreeMap<>();
for (String s : input) counts.merge(s, 1, Integer::sum);
System.out.println(counts); // {a=2, b=1, c=1}List<String> list = new ArrayList<>(List.of("c", "a", "b", "a"));
Wrong for (String s : list) if (s.equals("a")) list.remove(s); // ConcurrentModificationException
Right list.removeIf(s -> s.equals("a")); // [c, b]List<String> a = List.of("x", "y");
Wrong a.add("z"); // UnsupportedOperationException
List<String> b = Arrays.asList("x", "y");
b.set(0, "w"); // allowed: writes through to the array
Wrong b.add("z"); // UnsupportedOperationException
Right List<String> c = new ArrayList<>(List.of("x", "y")); // a list that can growSolve it
Find the first character that does not repeat
Given a string such as "swiss", return the first character that appears exactly once, here 'w'. Strings can be long,
so the interviewer wants better than comparing every pair.
- Clarify. Case-sensitive? Assume yes. If no character is unique, as in
"aabb", return an emptyOptional. - Start from the naive answer. For each character, scan the whole string: O(n²). Say it, then improve it.
- Count in one pass. A map from character to count gives O(n). It must remember insertion order to know which unique
character came first, so use
LinkedHashMap, notHashMap. - Scan the counts. Walk the map’s entries in order and return the first with count 1.
- Check.
"swiss"gives'w',"aabb"and""give empty. Time O(n), extra space O(k) for k distinct characters.
static Optional<Character> firstUnique(String s) {
Map<Character, Integer> counts = new LinkedHashMap<>();
for (char c : s.toCharArray()) counts.merge(c, 1, Integer::sum);
for (Map.Entry<Character, Integer> e : counts.entrySet()) {
if (e.getValue() == 1) return Optional.of(e.getKey());
}
return Optional.empty();
}How to answer
- List: ordered, indexed, duplicates allowed; ArrayList by default.
- Set: no duplicates, judged by equals and hashCode, or by compareTo in a TreeSet.
- Map: unique keys, each mapped to one value; HashMap by default.
- List, Set and Queue extend Collection; Map is not a Collection.
Common mistakes
- Saying a Set never keeps order; LinkedHashSet keeps insertion order and TreeSet keeps elements sorted.
- Calling Map a Collection, or expecting a for-each loop over the Map itself to compile.
Follow-up questions
ArrayList or LinkedList, which would you use and why?
ArrayList, almost always. It keeps the elements side by side in one array, so get(i) is O(1) and adding at the end is O(1) amortized; only an insert near the front shifts the rest. LinkedList keeps a node per element: adding or removing at either end is O(1), but get(i) follows links in O(n).
- ArrayList: get(i) O(1), add at the end O(1) amortized, add(0, x) O(n).
- LinkedList: add or remove at either end O(1), get(i) O(n).
- For a queue or a stack, prefer ArrayDeque to LinkedList.
See it in the infographic: ArrayList and LinkedList, three operations
Which collection would you choose to count words, track unique visitors, or keep tags sorted?
Ask three questions: pairs or single elements, duplicates or not, and which order. Word counts are pairs, so a HashMap, or a TreeMap when the report must be sorted. Unique visitors need no duplicates, so a HashSet. Sorted tags without duplicates fit a TreeSet. Everything else starts as an ArrayList.
- Pairs: HashMap, LinkedHashMap for insertion order, TreeMap for sorted keys.
- No duplicates: HashSet, LinkedHashSet or TreeSet, by the same order rule.
- Otherwise an ArrayList, sorted once if you need sorted output with duplicates.
Map<String, Integer> counts = new HashMap<>();
for (String word : words) counts.merge(word, 1, Integer::sum);
Set<String> visitors = new HashSet<>(visitorIds);
Set<String> sortedTags = new TreeSet<>(tags); What is the Big-O of the common collection operations?
ArrayList: get(i) is O(1), add at the end O(1) amortized, contains and an insert in the middle O(n). HashMap and HashSet: get, put and contains are O(1) on average. TreeMap and TreeSet: O(log n), because they are red-black trees. ArrayDeque: adding or removing at either end is O(1). PriorityQueue: offer and poll are O(log n), peek is O(1).
- Hash-based collections are O(1) on average and rely on a good hashCode.
- Tree-based collections are O(log n) and keep their keys sorted.
- contains on a List is O(n): it calls equals on one element after another.
See it in the infographic: ArrayList and LinkedList, three operations See it in the infographic: Which collection fits the need?
How do you make an unmodifiable list, and how is List.of different from Collections.unmodifiableList?
List.of, Set.of and Map.of build unmodifiable collections: add or set throws UnsupportedOperationException, and null elements are rejected. List.copyOf takes an unmodifiable copy of another list. Collections.unmodifiableList only wraps a list: the wrapper rejects writes, but changes to the original still show through it.
- List.of(1, 2).add(3) throws UnsupportedOperationException.
- List.of rejects null elements with a NullPointerException.
- unmodifiableList is a read-only view; List.copyOf is a copy.
List<String> backing = new ArrayList<>(List.of("a"));
List<String> view = Collections.unmodifiableList(backing);
List<String> copy = List.copyOf(backing);
backing.add("b");
System.out.println(view + " " + copy); // [a, b] [a] See it in the infographic: The collection interfaces and Map apart
What happens if you remove elements from an ArrayList while looping over it with for-each?
It typically fails with ConcurrentModificationException. The for-each loop uses the list's iterator, which is fail-fast: it remembers the list's modification count and throws when the list changes behind its back. Remove with removeIf, or with remove() on an explicit Iterator.
- The iterator checks a modification count on every next().
- list.remove inside the loop changes that count, so the next step throws.
- Use removeIf, or Iterator.remove() on an explicit iterator.
- Fail-fast is best effort: removing the second-to-last element ends the loop without an exception.
List<String> list = new ArrayList<>(List.of("c", "a", "b", "a"));
for (String s : list) if (s.equals("a")) list.remove(s); // ConcurrentModificationException
list.removeIf(s -> s.equals("a")); // [c, b]
Why is Map not a Collection?
A Collection holds single elements and a Map holds pairs, so add(E) does not fit put(K, V). Map offers three views instead: keySet() is a Set, values() is a Collection and entrySet() is a Set of entries.
When does LinkedList beat ArrayList?
Rarely. It wins only when you add or remove at the ends, or through an iterator already in place, and even then ArrayDeque is usually the better queue or stack. Each LinkedList node is a separate object, so it uses more memory and is slower to walk.
How does ArrayList grow?
The no-argument constructor starts with no array, allocates 10 slots on the first add, and when the array is full copies the elements into one about half as large again: 10, 15, 22. One add can cost O(n), but averaged over many adds it is O(1) amortized.
Check yourself
Show answers
- Map: Correct. Map holds key-value pairs and stands apart from Collection.
- List: Incorrect. List extends Collection.
- Set: Incorrect. Set extends Collection.
- Deque: Incorrect. Deque extends Queue, which extends Collection.
Show answers
- O(n): Correct. Every element shifts one slot right to make room at index 0.
- O(1): Incorrect. That is the LinkedList cost, which only relinks the head.
- O(log n): Incorrect. No tree is involved; the array shifts every element.
Show answers
- TreeSet: Correct. It drops duplicates and keeps elements sorted.
- HashSet: Incorrect. It drops duplicates but guarantees no order.
- LinkedHashSet: Incorrect. It keeps insertion order, not alphabetical order.
- ArrayList: Incorrect. It keeps duplicates.