Skip to content
javaintermediate

Java Collections Quiz

List, Set, Map, Queue, streams, and the Java Collections Framework.

7 questions

By EZ4Code Team

1. Which interface does ArrayList implement?

List
Set
Map
Queue
Explanation: `ArrayList` implements `List` (and `Collection`, `Iterable`). It's a resizable array allowing duplicates and ordered access. `LinkedList` also implements `List` (and `Deque`). For unique elements, use `Set` implementations like `HashSet`.

2. Which collection does NOT allow duplicate elements?

ArrayList
LinkedList
HashSet
Vector
Explanation: `HashSet` implements `Set`, which forbids duplicates. `ArrayList`, `LinkedList`, and `Vector` all implement `List`, which allows duplicates. Adding a duplicate to a `Set` silently fails (returns false).

3. What does this stream produce?

List<Integer> nums = List.of(1, 2, 3, 4, 5);
int sum = nums.stream()
    .filter(n -> n % 2 == 0)
    .mapToInt(n -> n)
    .sum();
System.out.println(sum);
15
6
10
9
Explanation: Filter keeps even numbers (2, 4). `mapToInt` converts to IntStream. `sum()` adds them: 2 + 4 = 6. The odd numbers (1, 3, 5) are filtered out.

4. Which Map implementation maintains insertion order?

HashMap
LinkedHashMap
TreeMap
Hashtable
Explanation: `LinkedHashMap` maintains insertion order (or access order, optionally). `HashMap` has no defined iteration order. `TreeMap` is sorted by keys (natural ordering or a Comparator). `Hashtable` is the legacy synchronized version with no order guarantee.

5. What is the time complexity of `HashMap.get()` on average?

O(1)
O(log n)
O(n)
O(n log n)
Explanation: Average case is O(1) — constant time lookup via hash table. Worst case (many hash collisions) degrades to O(n). Java 8+ uses a balanced tree for buckets with many collisions, improving worst case to O(log n).

6. What does `Collectors.toList()` do in a stream?

List<String> upper = names.stream()
    .map(String::toUpperCase)
    .collect(Collectors.toList());
Converts the stream to a List
Counts elements
Removes duplicates
Sorts the elements
Explanation: `Collectors.toList()` is a terminal operation that accumulates stream elements into a `List`. Other collectors include `toSet()`, `toMap()`, `groupingBy()`, and `joining()`. The stream is consumed after a terminal operation.

7. Which interface represents a FIFO queue in Java?

Queue
Stack
Deque
List
Explanation: `Queue` is the FIFO (first-in-first-out) interface. `Deque` extends `Queue` and supports both ends (LIFO and FIFO). `Stack` is a legacy class that's actually LIFO. For a typical queue, use `LinkedList` or `ArrayDeque` (preferred over `Stack`).

More java Quizzes