Practice Questions — Collections Framework - List, Set, Map
← Back to NotesTopic-Specific Questions
Question 1
Easy
What is the output?
ArrayList<String> list = new ArrayList<>();
list.add("A");
list.add("B");
list.add("C");
System.out.println(list);
System.out.println(list.size());ArrayList's toString prints elements in brackets.
[A, B, C]3Question 2
Easy
What is the output?
ArrayList<Integer> nums = new ArrayList<>();
nums.add(10);
nums.add(20);
nums.add(30);
System.out.println(nums.get(1));
System.out.println(nums.contains(20));
System.out.println(nums.indexOf(30));Indices start at 0. contains checks for value existence.
20true2Question 3
Easy
What is the output?
HashSet<String> set = new HashSet<>();
set.add("Java");
set.add("Python");
set.add("Java");
set.add("C++");
System.out.println(set.size());
System.out.println(set.contains("Python"));HashSet does not allow duplicates. "Java" is added twice.
3trueQuestion 4
Easy
What is the output?
HashMap<String, Integer> map = new HashMap<>();
map.put("A", 1);
map.put("B", 2);
map.put("C", 3);
System.out.println(map.get("B"));
System.out.println(map.get("D"));
System.out.println(map.size());get returns null for a non-existent key.
2null3Question 5
Easy
What is the output?
TreeSet<Integer> ts = new TreeSet<>();
ts.add(30);
ts.add(10);
ts.add(50);
ts.add(20);
ts.add(40);
System.out.println(ts);TreeSet maintains sorted order.
[10, 20, 30, 40, 50]Question 6
Medium
What is the output?
ArrayList<Integer> list = new ArrayList<>();
list.add(10);
list.add(20);
list.add(30);
list.remove(1);
System.out.println(list);
list.remove(Integer.valueOf(10));
System.out.println(list);remove(1) removes by index. remove(Integer.valueOf(10)) removes by value.
[10, 30][30]Question 7
Medium
What is the output?
HashMap<String, Integer> map = new HashMap<>();
map.put("Arjun", 85);
map.put("Kavya", 90);
map.put("Arjun", 95);
System.out.println(map.size());
System.out.println(map.get("Arjun"));Putting with an existing key replaces the value.
295Question 8
Medium
What is the output?
LinkedList<String> ll = new LinkedList<>();
ll.add("B");
ll.addFirst("A");
ll.addLast("C");
System.out.println(ll);
System.out.println(ll.getFirst());
System.out.println(ll.getLast());
ll.removeFirst();
System.out.println(ll);addFirst prepends, addLast appends.
[A, B, C]AC[B, C]Question 9
Medium
What is the output?
HashMap<String, Integer> map = new HashMap<>();
map.put("X", 1);
map.put("Y", 2);
map.put("Z", 3);
System.out.println(map.containsKey("Y"));
System.out.println(map.containsValue(5));
System.out.println(map.getOrDefault("W", -1));
System.out.println(map.keySet());containsKey/containsValue check existence. getOrDefault returns default for missing keys.
truefalse-1[X, Y, Z]Question 10
Medium
What is the output?
ArrayList<Integer> list = new ArrayList<>();
list.add(5);
list.add(3);
list.add(8);
list.add(1);
Collections.sort(list);
System.out.println(list);
System.out.println(Collections.min(list));
System.out.println(Collections.max(list));
Collections.reverse(list);
System.out.println(list);sort() sorts ascending. reverse() reverses the current order.
[1, 3, 5, 8]18[8, 5, 3, 1]Question 11
Hard
What is the output?
HashMap<String, Integer> map = new HashMap<>();
String[] words = {"a", "b", "a", "c", "b", "a"};
for (String w : words) {
map.put(w, map.getOrDefault(w, 0) + 1);
}
System.out.println(map);This is the word frequency counting pattern.
{a=3, b=2, c=1}Question 12
Hard
What is the output?
TreeMap<String, Integer> tm = new TreeMap<>();
tm.put("Banana", 2);
tm.put("Apple", 5);
tm.put("Cherry", 1);
System.out.println(tm);
System.out.println(tm.firstKey());
System.out.println(tm.lastKey());
System.out.println(tm.headMap("Cherry"));
System.out.println(tm.tailMap("Banana"));TreeMap is sorted by keys. headMap is exclusive, tailMap is inclusive.
{Apple=5, Banana=2, Cherry=1}AppleCherry{Apple=5, Banana=2}{Banana=2, Cherry=1}Question 13
Hard
What is the output?
HashSet<ArrayList<Integer>> set = new HashSet<>();
ArrayList<Integer> list1 = new ArrayList<>();
list1.add(1);
list1.add(2);
ArrayList<Integer> list2 = new ArrayList<>();
list2.add(1);
list2.add(2);
set.add(list1);
set.add(list2);
System.out.println(set.size());
list1.add(3);
set.add(list1);
System.out.println(set.size());ArrayList implements equals and hashCode based on contents. What happens when content changes?
12Question 14
Hard
What is the output?
HashMap<Integer, String> map = new HashMap<>();
map.put(1, "One");
map.put(2, "Two");
map.put(3, "Three");
map.forEach((k, v) -> System.out.println(k + " => " + v));
map.replaceAll((k, v) -> v.toUpperCase());
System.out.println(map);forEach iterates. replaceAll transforms all values.
1 => One2 => Two3 => Three{1=ONE, 2=TWO, 3=THREE}Question 15
Hard
What is the output?
ArrayList<Integer> list = new ArrayList<>();
list.add(1);
list.add(2);
list.add(3);
list.add(4);
list.add(5);
List<Integer> sub = list.subList(1, 4);
System.out.println(sub);
sub.set(0, 99);
System.out.println(list);subList returns a VIEW, not a copy. Changes to the sublist affect the original.
[2, 3, 4][1, 99, 3, 4, 5]Question 16
Hard
What is the output?
LinkedHashMap<String, Integer> lhm = new LinkedHashMap<>();
lhm.put("C", 3);
lhm.put("A", 1);
lhm.put("B", 2);
System.out.println(lhm);
TreeMap<String, Integer> tm = new TreeMap<>(lhm);
System.out.println(tm);
HashMap<String, Integer> hm = new HashMap<>(lhm);
System.out.println(hm.keySet());LinkedHashMap preserves insertion order. TreeMap sorts by key. HashMap has no guaranteed order.
{C=3, A=1, B=2}{A=1, B=2, C=3}[A, B, C] (order may vary for HashMap)Mixed & Application Questions
Question 1
Easy
What is the main difference between ArrayList and LinkedList?
Think about the underlying data structure.
ArrayList uses a dynamic array (contiguous memory), providing O(1) random access but O(n) insertions/deletions in the middle. LinkedList uses a doubly-linked list, providing O(1) insertions/deletions at ends but O(n) random access. Use ArrayList for most cases; LinkedList only when frequent insertions/deletions at the beginning are needed.
Question 2
Easy
How does HashSet ensure that elements are unique?
Think about hashCode() and equals().
When adding an element, HashSet calls
hashCode() to determine the bucket, then equals() to check if an identical element already exists in that bucket. If equals() returns true, the new element is rejected. This is why overriding equals() requires overriding hashCode().Question 3
Easy
What is the output?
HashSet<Integer> set = new HashSet<>();
System.out.println(set.add(10));
System.out.println(set.add(20));
System.out.println(set.add(10));
System.out.println(set);add() returns true if the element was added, false if already present.
truetruefalse[20, 10] (order may vary)Question 4
Medium
What is the output?
ArrayList<String> list = new ArrayList<>();
list.add("Banana");
list.add("Apple");
list.add("Cherry");
Collections.sort(list);
int idx = Collections.binarySearch(list, "Cherry");
System.out.println("Found at: " + idx);
idx = Collections.binarySearch(list, "Grape");
System.out.println("Not found: " + idx);binarySearch requires a sorted list. It returns negative if not found.
Found at: 2Not found: -4Question 5
Medium
When should you use HashMap vs TreeMap vs LinkedHashMap?
Think about ordering requirements.
HashMap: No ordering needed, fastest for put/get (O(1)). TreeMap: Need keys sorted in natural or custom order (O(log n) operations). LinkedHashMap: Need to preserve insertion order while maintaining O(1) operations. Use HashMap by default, TreeMap when you need sorted keys, LinkedHashMap when insertion order matters.
Question 6
Medium
What is the output?
ArrayList<Integer> list = new ArrayList<>(List.of(1, 2, 3, 4, 5));
list.removeIf(n -> n % 2 == 0);
System.out.println(list);removeIf removes all elements matching the predicate.
[1, 3, 5]Question 7
Hard
What is the output?
HashMap<String, ArrayList<Integer>> map = new HashMap<>();
map.computeIfAbsent("even", k -> new ArrayList<>()).add(2);
map.computeIfAbsent("odd", k -> new ArrayList<>()).add(1);
map.computeIfAbsent("even", k -> new ArrayList<>()).add(4);
map.computeIfAbsent("odd", k -> new ArrayList<>()).add(3);
System.out.println(map);computeIfAbsent creates a new value only if the key is absent. If present, it returns the existing value.
{even=[2, 4], odd=[1, 3]}Question 8
Hard
What happens internally when a HashMap has many hash collisions?
Think about what happens when multiple keys hash to the same bucket.
When multiple keys hash to the same bucket, HashMap stores them in a linked list (chaining). Since Java 8, if a bucket grows beyond 8 entries (TREEIFY_THRESHOLD), the linked list is converted to a balanced red-black tree, improving worst-case lookup from O(n) to O(log n). This prevents denial-of-service attacks that exploit hash collisions.
Question 9
Hard
What is the output?
TreeSet<String> set = new TreeSet<>((a, b) -> b.compareTo(a));
set.add("Arjun");
set.add("Kavya");
set.add("Ravi");
set.add("Priya");
System.out.println(set);
System.out.println(set.first());
System.out.println(set.last());The comparator reverses the natural order (b.compareTo(a) instead of a.compareTo(b)).
[Ravi, Priya, Kavya, Arjun]RaviArjunQuestion 10
Medium
Why should you use
List as the reference type instead of ArrayList?Think about programming to an interface.
Using the interface type (
List) instead of the implementation type (ArrayList) follows the "program to an interface" principle. It allows you to swap implementations later (e.g., change to LinkedList) without modifying code that uses the variable. It also documents that the code only relies on List behavior, not ArrayList-specific features.Multiple Choice Questions
MCQ 1
Which collection allows duplicate elements?
Answer: C
C is correct.
C is correct.
ArrayList (a List) allows duplicates. All Set implementations (HashSet, TreeSet, LinkedHashSet) reject duplicates.MCQ 2
What does HashMap.get(key) return if the key does not exist?
Answer: C
C is correct.
C is correct.
get() returns null for a non-existent key. Use getOrDefault(key, defaultValue) to avoid null.MCQ 3
Which collection maintains elements in sorted order?
Answer: C
C is correct.
C is correct.
TreeSet uses a Red-Black tree to maintain elements in sorted order. ArrayList and LinkedList maintain insertion order. HashSet has no guaranteed order.MCQ 4
What is the time complexity of ArrayList.get(index)?
Answer: B
B is correct. ArrayList uses a dynamic array with contiguous memory. Accessing by index is a simple offset calculation, which is O(1).
B is correct. ArrayList uses a dynamic array with contiguous memory. Accessing by index is a simple offset calculation, which is O(1).
MCQ 5
Can collections store primitive types like int or char?
Answer: B
B is correct. Collections use generics which require reference types. Use wrapper classes:
B is correct. Collections use generics which require reference types. Use wrapper classes:
ArrayList<Integer> instead of ArrayList<int>. Java autoboxes and unboxes automatically.MCQ 6
What exception is thrown when modifying a list during a for-each loop?
Answer: B
B is correct. Modifying a collection during a for-each loop (which uses an Iterator internally) causes
B is correct. Modifying a collection during a for-each loop (which uses an Iterator internally) causes
ConcurrentModificationException. Use Iterator.remove() or removeIf() instead.MCQ 7
Which Map implementation maintains insertion order?
Answer: C
C is correct.
C is correct.
LinkedHashMap maintains insertion order using a doubly-linked list. HashMap has no order. TreeMap sorts by key.MCQ 8
What must you override along with equals() for correct HashSet behavior?
Answer: C
C is correct. The hashCode/equals contract states: if two objects are equal, they must have the same hashCode. Without overriding hashCode, equal objects may end up in different buckets.
C is correct. The hashCode/equals contract states: if two objects are equal, they must have the same hashCode. Without overriding hashCode, equal objects may end up in different buckets.
MCQ 9
Which is true about Map in the Collections Framework?
Answer: B
B is correct. Map stores key-value pairs and does NOT extend the Collection interface. However, it is considered part of the Collections Framework.
B is correct. Map stores key-value pairs and does NOT extend the Collection interface. However, it is considered part of the Collections Framework.
MCQ 10
What does Collections.unmodifiableList() return?
Answer: B
B is correct.
B is correct.
unmodifiableList() returns a read-only view of the list. Any attempt to add, remove, or set elements throws UnsupportedOperationException. It is a view, not a copy.MCQ 11
What is the average time complexity of HashMap.get(key)?
Answer: C
C is correct. HashMap uses hashing to directly compute the bucket location, giving O(1) average-case get/put. In the worst case (all keys collide), it degrades to O(n) (or O(log n) with treeification in Java 8+).
C is correct. HashMap uses hashing to directly compute the bucket location, giving O(1) average-case get/put. In the worst case (all keys collide), it degrades to O(n) (or O(log n) with treeification in Java 8+).
MCQ 12
When does a HashMap bucket convert from a linked list to a tree (Java 8+)?
Answer: B
B is correct. In Java 8+, when a bucket (chain) has more than 8 entries (TREEIFY_THRESHOLD), it converts from a linked list to a red-black tree for O(log n) lookup instead of O(n).
B is correct. In Java 8+, when a bucket (chain) has more than 8 entries (TREEIFY_THRESHOLD), it converts from a linked list to a red-black tree for O(log n) lookup instead of O(n).
MCQ 13
What is the difference between Comparable and Comparator?
Answer: B
B is correct.
B is correct.
Comparable is implemented by the class itself (compareTo() method, defines natural ordering). Comparator is a separate class/lambda that defines a custom ordering externally.MCQ 14
What does HashMap do when two different keys have the same hashCode?
Answer: C
C is correct. When two keys have the same hashCode (collision), both entries are stored in the same bucket. HashMap uses chaining (linked list or tree) within the bucket and uses
C is correct. When two keys have the same hashCode (collision), both entries are stored in the same bucket. HashMap uses chaining (linked list or tree) within the bucket and uses
equals() to distinguish between keys.Coding Challenges
Challenge 1: Remove Duplicates from ArrayList
EasyGiven an ArrayList with duplicates, create a new list with duplicates removed while maintaining order. Use LinkedHashSet.
Sample Input
[4, 2, 3, 2, 1, 4, 3, 5]
Sample Output
Original: [4, 2, 3, 2, 1, 4, 3, 5]
Unique: [4, 2, 3, 1, 5]
Preserve insertion order. Use LinkedHashSet.
import java.util.*;
public class Main {
public static void main(String[] args) {
ArrayList<Integer> list = new ArrayList<>(Arrays.asList(4, 2, 3, 2, 1, 4, 3, 5));
System.out.println("Original: " + list);
ArrayList<Integer> unique = new ArrayList<>(new LinkedHashSet<>(list));
System.out.println("Unique: " + unique);
}
}Challenge 2: Student Grade Book with HashMap
MediumCreate a grade book using HashMap> where keys are student names and values are lists of marks. Add marks for 3 students. Calculate and print each student's average marks sorted by name.
Sample Input
Arjun: [85, 90, 78], Kavya: [92, 88, 95], Ravi: [70, 75, 80]
Sample Output
Arjun: [85, 90, 78] avg=84.33
Kavya: [92, 88, 95] avg=91.67
Ravi: [70, 75, 80] avg=75.00
Sort output by student name. Calculate average to 2 decimal places.
import java.util.*;
public class Main {
public static void main(String[] args) {
HashMap<String, ArrayList<Integer>> grades = new HashMap<>();
grades.put("Arjun", new ArrayList<>(Arrays.asList(85, 90, 78)));
grades.put("Kavya", new ArrayList<>(Arrays.asList(92, 88, 95)));
grades.put("Ravi", new ArrayList<>(Arrays.asList(70, 75, 80)));
TreeMap<String, ArrayList<Integer>> sorted = new TreeMap<>(grades);
for (Map.Entry<String, ArrayList<Integer>> e : sorted.entrySet()) {
double avg = e.getValue().stream().mapToInt(Integer::intValue).average().orElse(0);
System.out.printf("%s: %s avg=%.2f%n", e.getKey(), e.getValue(), avg);
}
}
}Challenge 3: Find First Non-Repeating Character
MediumGiven a string, find the first character that does not repeat. Use LinkedHashMap to maintain insertion order while counting frequencies.
Sample Input
"aabbcdeff"
Sample Output
First non-repeating: c
Use LinkedHashMap for O(n) solution. Handle case where all characters repeat.
import java.util.*;
public class Main {
static Character firstNonRepeating(String s) {
LinkedHashMap<Character, Integer> freq = new LinkedHashMap<>();
for (char c : s.toCharArray()) {
freq.put(c, freq.getOrDefault(c, 0) + 1);
}
for (Map.Entry<Character, Integer> e : freq.entrySet()) {
if (e.getValue() == 1) return e.getKey();
}
return null;
}
public static void main(String[] args) {
String s = "aabbcdeff";
Character result = firstNonRepeating(s);
System.out.println("First non-repeating: " + (result != null ? result : "none"));
}
}Challenge 4: Group Students by Grade
HardGiven a list of (name, marks) pairs, group students by grade: A (90+), B (80-89), C (70-79), D (below 70). Use HashMap> where keys are grades and values are student name lists. Print groups sorted by grade.
Sample Input
Arjun:85, Kavya:92, Ravi:70, Priya:65, Deepak:88, Meera:95
Sample Output
A: [Kavya, Meera]
B: [Arjun, Deepak]
C: [Ravi]
D: [Priya]
Use computeIfAbsent for clean grouping. Sort output by grade.
import java.util.*;
public class Main {
static String getGrade(int marks) {
if (marks >= 90) return "A";
if (marks >= 80) return "B";
if (marks >= 70) return "C";
return "D";
}
public static void main(String[] args) {
Map<String, Integer> students = Map.of(
"Arjun", 85, "Kavya", 92, "Ravi", 70,
"Priya", 65, "Deepak", 88, "Meera", 95
);
TreeMap<String, ArrayList<String>> groups = new TreeMap<>();
for (Map.Entry<String, Integer> e : students.entrySet()) {
String grade = getGrade(e.getValue());
groups.computeIfAbsent(grade, k -> new ArrayList<>()).add(e.getKey());
}
for (Map.Entry<String, ArrayList<String>> e : groups.entrySet()) {
Collections.sort(e.getValue());
System.out.println(e.getKey() + ": " + e.getValue());
}
}
}Challenge 5: LRU Cache Simulation
HardImplement a simple LRU (Least Recently Used) cache using LinkedHashMap with access-order. The cache should hold at most 3 entries. When a new entry is added and the cache is full, the least recently accessed entry is removed. Test with a sequence of get/put operations.
Sample Input
put(1,'A'), put(2,'B'), put(3,'C'), get(1), put(4,'D')
Sample Output
After puts: {1=A, 2=B, 3=C}
After get(1): accessed A
After put(4,D): {3=C, 1=A, 4=D} (2=B evicted)
Use LinkedHashMap with accessOrder=true and override removeEldestEntry.
import java.util.*;
class LRUCache<K, V> extends LinkedHashMap<K, V> {
private int capacity;
LRUCache(int capacity) {
super(capacity, 0.75f, true); // accessOrder=true
this.capacity = capacity;
}
@Override
protected boolean removeEldestEntry(Map.Entry<K, V> eldest) {
return size() > capacity;
}
}
public class Main {
public static void main(String[] args) {
LRUCache<Integer, String> cache = new LRUCache<>(3);
cache.put(1, "A");
cache.put(2, "B");
cache.put(3, "C");
System.out.println("After puts: " + cache);
String val = cache.get(1);
System.out.println("After get(1): accessed " + val);
cache.put(4, "D"); // Evicts least recently used (2=B)
System.out.println("After put(4,D): " + cache + " (2=B evicted)");
}
}Need to Review the Concepts?
Go back to the detailed notes for this chapter.
Read Chapter NotesWant to learn Java with a live mentor?
Explore our Java Masterclass