Practice: Collections & Generics Drill
50 min · Intermediate
Need help? Ask a tutor on WhatsApp (opens in a new tab)A collections round mixes four kinds of questions: "which collection would you use?", predict-the-output snippets, short coding problems and "how does it work inside?". The interviewer checks that you reason from the operations you need, not from memory.
Which collection would you use? A four-question method
Choosing a collection means picking the class from the operations you need, not from habit: key-value or single items, unique or not, which order, and how many threads.
Interviewers give a situation and ask which collection fits. The program picks one collection for each of four hostel-app needs.
Example 1 · Picking collections for a hostel app
import java.util.ArrayDeque;import java.util.Deque;import java.util.LinkedHashSet;import java.util.PriorityQueue;import java.util.Set;import java.util.TreeMap;
public class PickCollectionDemo { record Complaint(String room, int priority) {}
public static void main(String[] args) { // Unique visitors, in the order they came: LinkedHashSet Set<String> visitors = new LinkedHashSet<>(); for (String v : new String[] {"Asha", "Ravi", "Asha", "Kiran"}) visitors.add(v); System.out.println("Visitors: " + visitors);
// Room numbers sorted, with "next free room after 104": TreeMap TreeMap<Integer, String> rooms = new TreeMap<>(); rooms.put(101, "full"); rooms.put(105, "free"); rooms.put(110, "free"); System.out.println("First room after 104: " + rooms.ceilingKey(104));
Deque<String> undo = new ArrayDeque<>(); undo.push("allot 101"); undo.push("allot 105"); System.out.println("Undo: " + undo.pop());
// Most urgent complaint first: PriorityQueue PriorityQueue<Complaint> queue = new PriorityQueue<>((a, b) -> Integer.compare(b.priority(), a.priority())); queue.add(new Complaint("101", 2)); queue.add(new Complaint("110", 5)); queue.add(new Complaint("105", 3)); System.out.println("Fix first: room " + queue.poll().room()); }}Visitors: [Asha, Ravi, Kiran] First room after 104: 105 Undo: allot 105 Fix first: room 110
What this code does
- Each requirement maps to one class: unique plus order is LinkedHashSet, nearest key is TreeMap, last-in-first-out is ArrayDeque, most urgent first is PriorityQueue.
- In an interview, say the requirement and the class together: "next room after 104 needs a sorted map, so TreeMap with
ceilingKey".
Pick a collection from the operations, not from habit. Ask four questions in order and say them aloud: do I need key-value pairs (Map) or single items? Must items be unique (Set)? Does order matter: insertion, sorted, or first-in-first-out? Will several threads change it? Revise: Choosing a collection (opens in a new tab).
Then name the class and one reason, like "LinkedHashMap, because I need O(1) lookup and the order users signed up".
- Lookup by key →
HashMap; plus insertion order →LinkedHashMap; plus sorted or nearest key →TreeMap. - Unique items →
HashSet; keep order →LinkedHashSet; sorted →TreeSet. - Queue or stack →
ArrayDeque; always take the smallest or largest →PriorityQueue. - Index access, most cases →
ArrayList; many threads →ConcurrentHashMap,CopyOnWriteArrayList.
Order of execution
The four-question method
Put the questions in the order you ask them when choosing a collection.
Predict the output: maps, sets and iterators
The put return value is the previous value stored for that key, or null if there was none. A put on an existing key replaces the value and returns the old one.
Output questions test a handful of rules. The program runs five snippets in one run, so you can check each prediction.
Example 2 · Five predict-the-output snippets in one run
import java.util.ArrayList;import java.util.HashMap;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;import java.util.Set;import java.util.TreeSet;
public class PredictDrillDemo { public static void main(String[] args) { Map<String, Integer> m = new HashMap<>(); System.out.println("1: " + m.put("A", 1) + " " + m.put("A", 2) + " " + m.get("A"));
Map<String, Integer> lm = new LinkedHashMap<>(); lm.put("x", 1); lm.put("y", 2); lm.put("x", 3); System.out.println("2: " + lm);
Set<String> ts = new TreeSet<>(String.CASE_INSENSITIVE_ORDER); ts.add("upi"); ts.add("UPI"); ts.add("Card"); System.out.println("3: " + ts);
List<Integer> list = new ArrayList<>(List.of(10, 20, 30)); list.remove(Integer.valueOf(10)); list.remove(0); System.out.println("4: " + list);
List<String> names = new ArrayList<>(List.of("a", "b", "c")); for (String s : names) { if (s.equals("b")) names.remove(s); } System.out.println("5: " + names); }}1: null 1 2
2: {x=3, y=2}
3: [Card, upi]
4: [30]
5: [a, c]What this code does
- 1: the first
putreturnsnull(no old value), the second returns the old value 1. 2: replacing x keeps its position. 3: the case-insensitive comparator treats "UPI" as a duplicate of "upi". - 4: removing the value 10 leaves [20, 30], then
remove(0)removes index 0. 5: "b" is the second-to-last element, so the loop ends without an exception.
Is the map or set ordered, and how? Does a put replace a value? Does the loop change the collection it walks?
Write the state of the collection after each line, as in a dry run. Most wrong answers come from guessing HashMap print order or forgetting that a duplicate put returns the old value.
puton an existing key replaces the value, returns the old one, and keeps the position in a LinkedHashMap.addon a set returnsfalsefor a duplicate; a TreeSet's duplicate rule iscompareTo.- Adding or removing inside for-each throws CME, except the second-to-last removal.
remove(1)onList<Integer>removes index 1;List.ofandArrays.asListcannot grow.
Predict the output
Predict the output
Dry-run each snippet and pick what it prints.
Round 1 of 3
Coding questions: word frequency, first non-repeating character, group anagrams
An anagram key is the sorted letters of a word. Words that are anagrams of each other share the same key, so a map from key to list groups them.
Three short problems appear again and again, and each is one pass with a map. The programs count words, find the first unique character and group anagrams.
Example 3 · Word frequency and first non-repeating character
import java.util.LinkedHashMap;import java.util.Map;import java.util.TreeMap;
public class FrequencyDemo { static Map<String, Integer> wordFrequency(String text) { Map<String, Integer> counts = new TreeMap<>(); // sorted output for (String w : text.toLowerCase().split("\\s+")) { counts.merge(w, 1, Integer::sum); } return counts; }
static char firstNonRepeating(String s) { Map<Character, Integer> counts = new LinkedHashMap<>(); // keeps first-seen order for (char c : s.toCharArray()) { counts.merge(c, 1, Integer::sum); } for (Map.Entry<Character, Integer> e : counts.entrySet()) { if (e.getValue() == 1) { return e.getKey(); } } return '_'; }
public static void main(String[] args) { System.out.println(wordFrequency("UPI payment done UPI refund payment UPI")); System.out.println("First unique in 'swiss': " + firstNonRepeating("swiss")); System.out.println("First unique in 'aabb': " + firstNonRepeating("aabb")); }}{done=1, payment=2, refund=1, upi=3}
First unique in 'swiss': w
First unique in 'aabb': _What this code does
mergeadds 1 to an existing count or inserts 1 for a new word, so each problem is one O(n) pass.- The LinkedHashMap keeps letters in first-seen order, so the first entry with count 1 is the answer; '_' means there is none.
Example 4 · Group anagrams with a sorted-letters key
import java.util.ArrayList;import java.util.Arrays;import java.util.LinkedHashMap;import java.util.List;import java.util.Map;
public class GroupAnagramsDemo { static List<List<String>> groupAnagrams(String[] words) { Map<String, List<String>> groups = new LinkedHashMap<>(); for (String w : words) { char[] letters = w.toCharArray(); Arrays.sort(letters); String key = new String(letters); groups.computeIfAbsent(key, k -> new ArrayList<>()).add(w); } return new ArrayList<>(groups.values()); }
public static void main(String[] args) { String[] words = {"listen", "silent", "rat", "tar", "enlist", "art", "hello"}; for (List<String> group : groupAnagrams(words)) { System.out.println(group); } }}[listen, silent, enlist] [rat, tar, art] [hello]
What this code does
- Anagrams have the same letters, so sorting the letters gives them the same key: "eilnst" for listen, silent and enlist.
computeIfAbsentcreates each group's list on first use. A LinkedHashMap keeps groups in first-seen order, which makes the output easy to check.
Word frequency: merge(word, 1, Integer::sum). First non-repeating character: count with a LinkedHashMap (or an int[26]), then take the first count of 1. Group anagrams: sort each word's letters to make a key, then computeIfAbsent(key, k -> new ArrayList<>()).add(word).
State the complexity when you finish: frequency and first unique are O(n); group anagrams is O(n · k log k) for n words of length k, because of sorting each word. Revise: Counting and grouping (opens in a new tab).
Find the bug
Find the coding bug
Each solution has one wrong line. Tap it, then check the fix.
Count how often each word appears.
Round 1 of 3Explain-the-internals round
Internals questions want a fixed sequence of facts, delivered in under a minute each. Practise these three until they come out in order without pauses.
Revise: How a HashMap works (opens in a new tab), ArrayList internals (opens in a new tab) and HashSet (opens in a new tab).
- ArrayList:
Object[], 10 slots on the first add, grows toold + old/2with a copy,getO(1), add at end O(1) on average, middle insert O(n). - HashMap: bucket array,
hashCodespread and masked with(n - 1) & hash, chain thenequals, tree past 8 nodes (Java 8), load factor 0.75, doubles on resize, one null key. - HashSet: a HashMap with elements as keys and one dummy value; duplicates are found by
hashCodethenequals;addreturnsfalsefor a duplicate.
Next step
Check your understanding
12 quick questions