Java Interview Preparation

Collections Interview Questions

Lists, sets, maps, queues, iterators, generics, sorting, streams, concurrency, and collection performance.

Collections Interview Focus

Lists, sets, maps, queues, iterators, generics, sorting, streams, concurrency, and collection performance.

Collections interview questions

Interview questions

102 matching

1. What is the Java Collections Framework? Beginner

It is a group of interfaces, implementations, and algorithms for storing and processing groups of objects with type safety and reusable behavior.

List<String> technologies = new ArrayList<>();
technologies.add("Java");

2. What is a collection in Java? Beginner

A collection is an object that stores multiple elements as one unit, such as a list of employees or a set of IDs.

3. What is the difference between Collection and Collections? Beginner

Collection is the root interface for List, Set, and Queue. Collections is a utility class that provides static methods for sorting, searching, reversing, and synchronized wrappers.

4. What is the difference between Collection and Map? Beginner

Collection stores individual elements. Map stores key-value pairs, has unique keys, and does not extend Collection.

5. What are the main Collections Framework interfaces? Beginner

The main interfaces are List, Set, Queue, Deque, and Map. They describe ordered values, unique values, processing queues, double-ended queues, and key-value associations.

6. What is the Java Collections Framework hierarchy? Intermediate

Iterable is the parent of Collection, which branches into List, Set, and Queue. Map has a separate hierarchy with HashMap, LinkedHashMap, TreeMap, and concurrent implementations.

7. What is the difference between List, Set, and Map? Beginner

List preserves order and allows duplicates, Set stores unique values, and Map stores unique keys with associated values.

8. Why are generics used with collections? Beginner

Generics provide compile-time type safety, remove most casts, improve readability, and prevent unrelated object types from entering a collection.

List<String> technologies = new ArrayList<>();

9. What is the List interface? Beginner

List is an ordered collection that permits duplicates, supports index-based access, and commonly allows null values.

10. What is ArrayList? Beginner

ArrayList is a resizable-array List implementation suited to frequent reads, indexed access, and additions at the end.

List<String> courses = new ArrayList<>();
courses.add("Java");

11. How does ArrayList work internally? Intermediate

ArrayList stores elements in an internal array. When it fills, a larger array is allocated and existing elements are copied.

12. What is the initial capacity of ArrayList? Advanced

An empty ArrayList commonly has no allocated storage until its first addition; standard implementations commonly allocate capacity 10 then. Treat this as implementation behavior, not a general API guarantee.

13. How does ArrayList increase capacity? Intermediate

When full, it grows its internal array by an implementation-defined amount, commonly around 50 percent, and copies the existing values.

14. What is the time complexity of ArrayList operations? Intermediate

Indexed get and set are O(1), append is amortized O(1), while search and insertion or removal near the beginning are generally O(n).

15. What is LinkedList? Beginner

LinkedList is a doubly linked implementation of List, Queue, and Deque. Each node holds a value and links to neighboring nodes.

16. What is the difference between ArrayList and LinkedList? Beginner

ArrayList has fast indexed access and lower overhead. LinkedList supports operations at known ends or nodes but has slow traversal and extra node memory.

17. When should ArrayList be preferred over LinkedList? Beginner

Prefer ArrayList for random access, iteration-heavy workloads, additions at the end, and most general application lists.

18. When should LinkedList be used? Intermediate

Use it when the abstraction is genuinely a deque or queue and operations occur at both ends. ArrayDeque is often a better stack or queue implementation.

19. What is Vector? Beginner

Vector is a legacy synchronized resizable-array List. Modern code usually prefers ArrayList or a specific concurrent list implementation.

20. What is Stack in Java? Beginner

Stack is a legacy LIFO class. ArrayDeque is generally preferred for stack behavior because it is modern and avoids unnecessary synchronization.

Deque<String> stack = new ArrayDeque<>();
stack.push("Java");

21. How do you create an immutable list? Beginner

Use List.of or an unmodifiable copy when a list must not be changed. List.of rejects null values.

List<String> values = List.of("Java", "Kafka");

22. What is the difference between Arrays.asList and List.of? Intermediate

Arrays.asList is fixed-size and backed by an array, allowing replacement. List.of is immutable and rejects null values.

23. How do you convert an array into a mutable list? Beginner

Create a new ArrayList from Arrays.asList so structural changes are supported.

List<String> list = new ArrayList<>(Arrays.asList(values));

24. What is the Set interface? Beginner

Set is a collection that prevents duplicate elements according to equality or ordering rules.

25. What is HashSet? Beginner

HashSet uses hashing for unique membership checks, provides average constant-time operations, has no order guarantee, and permits one null.

26. How does HashSet work internally? Intermediate

HashSet stores elements as keys in an internal HashMap with a shared dummy value. Map key uniqueness gives Set uniqueness.

27. How does HashSet detect duplicates? Intermediate

It uses hashCode to select a bucket and equals to compare candidates. Correct custom objects must override both methods consistently.

28. What is LinkedHashSet? Beginner

LinkedHashSet provides unique values like HashSet while maintaining insertion order using linked ordering information.

29. What is TreeSet? Beginner

TreeSet stores unique values in sorted order using natural ordering or a supplied Comparator. Operations are generally O(log n).

30. What is the difference between HashSet, LinkedHashSet, and TreeSet? Intermediate

HashSet optimizes uniqueness without order, LinkedHashSet preserves insertion order, and TreeSet maintains sorted order with tree-based operations.

31. Can HashSet store null values? Beginner

Yes. HashSet permits one null value because duplicate null additions are ignored.

32. Why does TreeSet generally not allow null? Intermediate

TreeSet compares elements to maintain order, and null normally cannot be compared with non-null values.

33. What is a Map in Java? Beginner

Map stores key-value pairs. Keys are unique, while values may be duplicated.

34. What is HashMap? Beginner

HashMap is a hash-based Map that provides average constant-time lookup, permits one null key and multiple null values, and is not thread-safe.

35. How does HashMap work internally? Advanced

HashMap hashes a key, selects a bucket, compares existing keys with equals, and adds or replaces an entry. Collision-heavy buckets may use tree structures.

36. What is a hash collision? Intermediate

A collision occurs when different keys map to the same bucket. HashMap stores and compares colliding entries using equality.

37. What happens when the same key is added twice to HashMap? Beginner

The new value replaces the old value and the map size does not increase.

38. Can HashMap store null keys and values? Beginner

Yes. HashMap permits one null key and any number of null values.

39. Why should HashMap keys be immutable? Advanced

Changing fields used by hashCode or equals after insertion can move the logical key to a different bucket and make it unreachable.

40. What is the equals and hashCode contract? Intermediate

Equal objects must return the same hash code. Equal hash codes do not necessarily mean objects are equal, and equality-related state should remain stable.

41. What happens if equals is overridden but hashCode is not? Intermediate

Hash-based collections can place equal objects in different buckets, causing duplicate logical values and failed lookup or removal.

42. What is LinkedHashMap? Beginner

LinkedHashMap is a HashMap with predictable insertion order, or access order when configured for cache-like behavior.

43. Can LinkedHashMap maintain access order? Intermediate

Yes. Its accessOrder constructor option moves accessed entries toward the end and can support an LRU cache.

44. What is TreeMap? Beginner

TreeMap stores keys in sorted order using a balanced tree and supports range and navigation operations in O(log n).

45. What is the difference between HashMap, LinkedHashMap, and TreeMap? Intermediate

HashMap provides fast unordered lookup, LinkedHashMap preserves insertion or access order, and TreeMap sorts keys with logarithmic operations.

46. What is Hashtable? Beginner

Hashtable is a legacy synchronized Map that rejects null keys and values. Modern code generally uses ConcurrentHashMap for concurrent access.

47. What is the difference between HashMap and Hashtable? Beginner

HashMap is unsynchronized and permits nulls. Hashtable synchronizes methods, rejects nulls, and is a legacy implementation.

48. What is ConcurrentHashMap? Intermediate

ConcurrentHashMap is a scalable thread-safe Map that supports concurrent reads, updates, and atomic operations without one global application lock.

49. Why does ConcurrentHashMap not allow null keys or values? Advanced

A null result from get would be ambiguous: it could mean absent or present with null. Rejecting null removes that ambiguity.

50. What is the difference between HashMap and ConcurrentHashMap? Intermediate

HashMap is not thread-safe and permits nulls. ConcurrentHashMap supports concurrent mutation, rejects nulls, and provides weakly consistent iterators.

51. How do you iterate over a Map? Beginner

Use entrySet when both keys and values are needed, or Map.forEach for concise iteration.

map.forEach((key, value) -> System.out.println(key + "=" + value));

52. What is the difference between keySet, values, and entrySet? Beginner

keySet exposes keys, values exposes values, and entrySet exposes key-value pairs. Use entrySet when both are required.

53. What is a Queue? Beginner

Queue represents elements waiting for processing, commonly in FIFO order, with operations such as offer, poll, peek, add, and remove.

54. What is the difference between add and offer? Beginner

Both insert into a queue. add may throw when insertion fails, while offer returns false and is safer for capacity-restricted queues.

55. What is the difference between remove and poll? Beginner

Both remove the head. remove throws when empty, while poll returns null.

56. What is the difference between element and peek? Beginner

Both inspect the head without removing it. element throws when empty, while peek returns null.

57. What is PriorityQueue? Beginner

PriorityQueue removes elements according to priority rather than insertion order. Its default priority is the smallest natural value.

58. What is Deque? Beginner

Deque is a double-ended queue that supports adding and removing from both the front and back.

59. Why is ArrayDeque preferred over Stack? Beginner

ArrayDeque is modern, efficient, supports both stack and queue operations, and avoids legacy Stack synchronization overhead.

60. What is Iterator? Beginner

Iterator traverses collection elements using hasNext and next and can safely remove the current element with iterator.remove.

61. Why use Iterator when removing during iteration? Intermediate

Calling collection.remove during enhanced-for iteration can cause ConcurrentModificationException. Iterator.remove coordinates removal with traversal.

62. What is ListIterator? Intermediate

ListIterator is a list-specific iterator supporting forward and backward traversal, replacement, insertion, removal, and index queries.

63. What is the difference between Iterator and ListIterator? Beginner

Iterator supports broad forward traversal and removal. ListIterator works only with lists and also supports backward traversal, add, set, and indexes.

64. What is a fail-fast iterator? Intermediate

It may throw ConcurrentModificationException when it detects structural modification outside the iterator. This is a best-effort bug detector, not thread safety.

65. What is a fail-safe iterator? Advanced

Fail-safe is an informal term for snapshot or concurrent iterators that continue without immediately throwing on concurrent changes. Weakly consistent is more precise.

66. What is the difference between fail-fast and weakly consistent iterators? Advanced

Fail-fast iterators may report structural modification. Weakly consistent iterators tolerate concurrent changes and may reflect some, all, or none of them.

67. How do you sort a list? Beginner

Use Collections.sort, List.sort, or a Comparator. Comparator.reverseOrder provides descending natural order.

numbers.sort(Comparator.naturalOrder());

68. What is Comparable? Beginner

Comparable defines a type’s natural ordering through compareTo and is implemented by the class being sorted.

69. What is Comparator? Beginner

Comparator defines an external ordering strategy. Multiple comparators can sort the same class by different fields.

employees.sort(Comparator.comparing(Employee::getName));

70. What is the difference between Comparable and Comparator? Beginner

Comparable provides one natural order through compareTo. Comparator provides reusable external orders through compare and does not require changing the class.

71. How do you sort by multiple fields? Intermediate

Chain comparators with thenComparing so a secondary field is used when the primary values are equal.

employees.sort(Comparator.comparing(Employee::getName).thenComparingInt(Employee::getId));

72. How do you handle null values while sorting? Beginner

Use Comparator.nullsFirst or nullsLast around the real comparator.

73. What are concurrent collections? Beginner

They are collections designed for safe, scalable multi-threaded access, including ConcurrentHashMap, CopyOnWriteArrayList, BlockingQueue, and concurrent queues.

74. What is CopyOnWriteArrayList? Intermediate

It copies its backing array on each modification and is suitable for read-heavy, write-rare workloads with snapshot-style iteration.

75. What is BlockingQueue? Intermediate

BlockingQueue supports producer-consumer workflows by waiting when taking from empty queues or adding to full bounded queues.

BlockingQueue<Task> tasks = new LinkedBlockingQueue<>();

76. What is the difference between synchronized and concurrent collections? Advanced

Synchronized wrappers commonly use one collection-level lock. Concurrent collections use specialized algorithms and atomic operations for better scalability.

77. How do you filter a collection using streams? Beginner

Use stream.filter with a predicate and collect or toList the matching values.

var result = values.stream().filter(value -> value.startsWith("J")).toList();

78. How do you remove duplicates using streams? Beginner

Use distinct, which relies on equality semantics, then collect the stream result.

var unique = numbers.stream().distinct().toList();

79. How do you convert a list into a map? Intermediate

Use Collectors.toMap with key and value functions, and provide a merge function when duplicate keys are possible.

80. How do you group collection elements? Intermediate

Use Collectors.groupingBy with a classifier such as department or status.

81. How do you count duplicate elements in a list? Intermediate

Group by the element and use Collectors.counting as the downstream collector.

82. Which collection stores unique employee IDs? Beginner

Use HashSet for fast uniqueness, LinkedHashSet when insertion order matters, or TreeSet when sorted order is required.

83. Which collection stores employee IDs and details? Beginner

Use a Map with the employee ID as the key and Employee as the value.

Map<Long, Employee> employees = new HashMap<>();

84. Which collection maintains insertion order and prevents duplicates? Beginner

Use LinkedHashSet.

85. Which collection stores sorted unique values? Beginner

Use TreeSet.

86. Which collection is suitable for an LRU cache? Advanced

Use LinkedHashMap configured with access order and override removeEldestEntry, or use a dedicated cache library for production needs.

87. Which collection is suitable for producer-consumer processing? Beginner

Use BlockingQueue, such as LinkedBlockingQueue or ArrayBlockingQueue.

88. Which collection is suitable for a thread-safe read-heavy list? Intermediate

Use CopyOnWriteArrayList when reads dominate, writes are rare, and snapshot iteration is acceptable.

89. Which collection is suitable for a thread-safe shared cache? Intermediate

Use ConcurrentHashMap for concurrent key-value access. A dedicated cache library may be better for eviction, expiration, and statistics.

90. Can a collection store primitive values? Beginner

No. Collections store objects, so use wrapper types such as Integer instead of int. Java provides autoboxing and unboxing.

List<Integer> numbers = new ArrayList<>();

91. Why can List.remove remove an index instead of a value? Intermediate

For List<Integer>, remove(int) selects an index. Use remove(Integer.valueOf(value)) to select the value overload.

numbers.remove(Integer.valueOf(20));

92. Can a collection be modified during forEach? Beginner

Structural modification during iteration may throw ConcurrentModificationException. Prefer removeIf, an iterator, or a concurrent collection.

93. What happens when a mutable object in HashSet is modified? Advanced

If equality-related fields change, contains or remove may fail because the object is now associated with a different hash location.

94. Can TreeMap use custom objects as keys? Intermediate

Yes. Keys must implement Comparable or TreeMap must receive a Comparator.

95. What happens when compareTo returns zero for different objects? Advanced

Sorted collections treat the objects as equal for ordering, so TreeSet may keep one and TreeMap may replace a value.

96. Is HashMap iteration order guaranteed? Beginner

No. Use LinkedHashMap for insertion or access order and TreeMap for sorted key order.

97. Is HashMap thread-safe for reading? Advanced

Concurrent reads can be safe only after safe publication and when no thread mutates the map. Use an immutable map or ConcurrentHashMap for shared concurrent access.

98. What is the load factor in HashMap? Advanced

Load factor controls how full the table becomes before resizing. The common default is 0.75, balancing memory and collisions.

99. What is the initial capacity of HashMap? Advanced

Capacity is the number of internal buckets, while size is the number of entries. The common default capacity is 16 when storage initializes, but implementations may vary.

100. What happens when HashMap reaches its threshold? Advanced

It resizes the bucket array, redistributes entries, and continues with a larger capacity. Providing a suitable initial capacity can reduce expensive resizing.

101. What are the main Java collection performance differences? Advanced

ArrayList provides O(1) indexed access, hash collections average O(1) lookup, tree collections O(log n), and queue priority operations commonly O(log n). Always measure realistic workloads.

102. What are best practices for Java collections? Advanced

Program to interfaces, use generics, choose by access and ordering needs, prefer immutable values, implement equals and hashCode correctly, avoid unsafe modification, and use concurrent types for shared state.

How to Prepare for Java Technical Interviews

Use this Java technical interview question bank to revise core concepts and practise explaining your decisions clearly. The questions cover Java fundamentals, object-oriented programming, collections, exceptions, multithreading, Spring Boot, Hibernate, databases, and other topics used in real software development interviews.

Start with the fundamentals, then move to scenario-based questions and advanced topics. Filter questions by difficulty to build confidence gradually. A strong answer should define the concept, explain why it matters, and include a practical example when appropriate.

Continue your preparation with the Java tutorials, or explore all interview preparation tracks for managerial and company-focused questions.