Prev Next

Java / Java 21 Collection Framework features Interview questions

1. What is the Sequenced Collections feature introduced in Java 21? 2. What is the SequencedCollection interface? 3. What is the SequencedSet interface? 4. What is the SequencedMap interface? 5. What are the new methods added by the SequencedCollection interface? 6. What is the purpose of the reversed() method in Java 21 collections? 7. Define encounter order in the context of Sequenced Collections? 8. What are getFirst() and getLast() used for? 9. What are addFirst() and addLast() used for? 10. What are removeFirst() and removeLast() used for? 11. List the collection classes that implement SequencedCollection in Java 21? 12. List the collection classes that implement SequencedSet in Java 21? 13. List the collection classes that implement SequencedMap in Java 21? 14. What are firstEntry() and lastEntry() in SequencedMap? 15. What are putFirst() and putLast() in SequencedMap? 16. What are pollFirstEntry() and pollLastEntry()? 17. Describe the sequencedKeySet(), sequencedValues(), and sequencedEntrySet() methods? 18. How do you use getFirst() and getLast() on an ArrayList in Java 21? 19. How do you apply reversed() to a List in Java 21? 20. How do you use putFirst() on a LinkedHashMap? 21. Why was the Sequenced Collections API introduced in Java 21? 22. Why doesn't HashSet implement SequencedSet? 23. Why doesn't HashMap implement SequencedMap? 24. How does SequencedSet differ from a plain LinkedHashSet used before Java 21? 25. How does TreeSet implement SequencedSet given its natural ordering? 26. How does TreeMap support SequencedMap given its comparator-based ordering? 27. What is the difference between SequencedCollection and List? 28. What is the difference between SequencedSet and NavigableSet? 29. What is the difference between List.reversed() and Collections.reverse()? 30. What is the difference between removeFirst()/removeLast() on SequencedCollection and on Deque? 31. When should you choose SequencedMap over a regular Map? 32. When would you choose getFirst() over get(0) on a List? 33. What happens when you call getFirst() on an empty SequencedCollection? 34. What happens when you call reversed() on an immutable List returned by List.of()? 35. What happens when you modify the original collection after calling reversed() on it? 36. How is the encounter order of a LinkedHashSet determined when using SequencedSet methods? 37. How does LinkedHashMap's access-order mode interact with SequencedMap methods? 38. Why doesn't Set.of() return a SequencedSet? 39. Which is better and why: getFirst() or peekFirst() on an ArrayDeque? 40. How can you optimize iteration and access using SequencedCollection methods instead of manual indexing? 41. How can you optimize a producer-consumer pattern using ArrayDeque's sequenced methods? 42. How do you troubleshoot a NoSuchElementException thrown from a sequenced collection method? 43. How do you troubleshoot UnsupportedOperationException when calling addFirst() on an unmodifiable list? 44. Explain the internal working of the reversed() view for a List? 45. Explain the lifecycle of a view returned by SequencedMap.reversed()? 46. Explain the execution flow of putFirst() on a LinkedHashMap? 47. Explain the internal working of the retrofit strategy used to add Sequenced interfaces without breaking existing implementations? 48. Why is Deque now classified as a SequencedCollection? 49. What is the difference between SequencedCollection and the Queue interface? 50. Explain how record patterns in Java 21 complement processing elements of sequenced collections?

1. What is the Sequenced Collections feature introduced in Java 21?

Sequenced Collections, delivered through JEP 431 , is a set of new interfaces added in Java 21 that give collections with a defined encounter order a common way to access their first and last elements and to view them in reverse. Before Java 21, List had get(0) and index-based tricks, Deque had i...

Read full answer

2. What is the SequencedCollection interface?

SequencedCollection is a new interface in java.util that sits directly under Collection in the hierarchy and represents any collection whose elements have a well-defined encounter order, from first to last. It adds seven methods: addFirst(E) , addLast(E) , getFirst() , getLast() , removeFir...

Read full answer

3. What is the SequencedSet interface?

SequencedSet extends both Set and SequencedCollection , so it's a Set that also guarantees a defined encounter order and inherits the first/last/reversed methods. It overrides reversed() with a covariant return type, so calling reversed() on a SequencedSet gives back another SequencedSet...

Read full answer

4. What is the SequencedMap interface?

SequencedMap extends Map and adds methods for working with the first and last entries of a map that has a defined encounter order, plus a reversed() view of the whole map. Its new methods include firstEntry() , lastEntry() , pollFirstEntry() , pollLastEntry() , putFirst(K,V) , putLast(K...

Read full answer

5. What are the new methods added by the SequencedCollection interface?

SequencedCollection adds seven methods on top of what Collection already provides, giving every implementing type a consistent way to work with its ends. Method Purpose addFirst(E) Insert an element at the start addLast(E) Insert an element at the end getFirst() Read the first element getLast() R...

Read full answer

6. What is the purpose of the reversed() method in Java 21 collections?

reversed() gives you a view of a sequenced collection with its encounter order flipped, without copying any elements or building a new backing structure. Because it's a view, changes made through the reversed collection are reflected in the original, and changes to the original show up when you r...

Read full answer

7. Define encounter order in the context of Sequenced Collections?

Encounter order is the sequence in which a collection's elements are visited when you iterate over it - it defines which element is "first" and which is "last" for that collection. Some collections have a well-defined encounter order by design: a List follows index order, a LinkedHashSet / Linked...

Read full answer

8. What are getFirst() and getLast() used for?

getFirst() and getLast() return the first and last elements of a sequenced collection according to its encounter order, without removing them. On a List , they're equivalent to list.get(0) and list.get(list.size() - 1) , but they read more clearly and work the same way across every sequenced type...

Read full answer

9. What are addFirst() and addLast() used for?

addFirst(E) inserts an element at the beginning of a sequenced collection, and addLast(E) inserts one at the end, updating the encounter order accordingly. These were already familiar from Deque , but Java 21 makes them available on any type that implements SequencedCollection , including ArrayLi...

Read full answer

10. What are removeFirst() and removeLast() used for?

removeFirst() removes and returns the first element of a sequenced collection, while removeLast() does the same for the last element, shrinking the collection by one. They combine the read-and-remove step into a single call, which is convenient for stack- and queue-style processing where you repe...

Read full answer

11. List the collection classes that implement SequencedCollection in Java 21?

Every implementation of List qualifies, since a list's index order is already a well-defined encounter order - that includes ArrayList , LinkedList , Vector , Stack , and CopyOnWriteArrayList . Every implementation of Deque also qualifies, because Deque itself now extends SequencedCollection - th...

Read full answer

12. List the collection classes that implement SequencedSet in Java 21?

Class How it qualifies LinkedHashSet Implements SequencedSet directly - insertion order is its encounter order TreeSet Implements SequencedSet indirectly, through NavigableSet No other standard Set implementation qualifies. HashSet and its subclasses are left out because their iteration order isn...

Read full answer

13. List the collection classes that implement SequencedMap in Java 21?

Class How it qualifies LinkedHashMap Implements SequencedMap directly - insertion (or access) order is its encounter order TreeMap Implements SequencedMap indirectly, through NavigableMap HashMap , like HashSet , is excluded since hash-based maps don't guarantee any particular iteration order acr...

Read full answer

14. What are firstEntry() and lastEntry() in SequencedMap?

firstEntry() and lastEntry() return the first and last key-value pairs of a SequencedMap , wrapped as Map.Entry objects, without removing them from the map. LinkedHashMap < String, Integer > scores = new LinkedHashMap <> (); scores.put( "Ann" , 90 ); scores.put( "Ben" , 85 ); System.out.println(s...

Read full answer

15. What are putFirst() and putLast() in SequencedMap?

putFirst(K, V) inserts or moves a key-value pair to the front of a SequencedMap 's encounter order, and putLast(K, V) does the same at the end. If the key already exists, calling either method removes it from its current position and reinserts it at the requested end, updating the value - this ma...

Read full answer

16. What are pollFirstEntry() and pollLastEntry()?

pollFirstEntry() and pollLastEntry() remove and return the first and last entries of a SequencedMap , combining a read and a delete into one call. LinkedHashMap queue = new LinkedHashMap<>(); queue.put("job1", 1); queue.put("job2", 2); Map.Entry next = queue.poll...

Read full answer

17. Describe the sequencedKeySet(), sequencedValues(), and sequencedEntrySet() methods?

These three methods on SequencedMap return ordered, sequenced views of the map's keys, values, and entries - counterparts to the plain keySet() , values() , and entrySet() from Map . Method Returns sequencedKeySet() A SequencedSet of the keys, in encounter order sequencedValues() A SequencedCo...

Read full answer

18. How do you use getFirst() and getLast() on an ArrayList in Java 21?

Since ArrayList implements List , which now extends SequencedCollection , you can call getFirst() and getLast() directly on any ArrayList instance without any casting or extra setup. ArrayList < String > fruits = new ArrayList <> (List.of( "apple" , "banana" , "cherry" )); System.out.println(frui...

Read full answer

19. How do you apply reversed() to a List in Java 21?

Call .reversed() directly on any List instance - since List extends SequencedCollection , the method is available without any extra imports or wrapping. List < Integer > original = new ArrayList <> (List.of( 10 , 20 , 30 )); List < Integer > reversedView = original.reversed(); System.out.println(...

Read full answer

20. How do you use putFirst() on a LinkedHashMap?

Call putFirst(key, value) on any LinkedHashMap instance to insert a new entry, or move an existing one, to the front of its iteration order. LinkedHashMap recent = new LinkedHashMap<>(); recent.put("x", 1); recent.put("y", 2); recent.putFirst("z", 3); // order becomes z, x, y Thi...

Read full answer

21. Why was the Sequenced Collections API introduced in Java 21?

Before Java 21, working with the "ends" of a collection meant learning a different API for every type: list.get(0) for lists, deque.peekFirst() for deques, and no first-class method at all for grabbing the first entry of a LinkedHashMap or LinkedHashSet . This inconsistency made simple, common op...

Read full answer

22. Why doesn't HashSet implement SequencedSet?

SequencedSet makes a contractual promise: the set has a defined, stable encounter order, and calling getFirst() / getLast() or reversed() gives meaningful, predictable results. HashSet can't honor that promise. Its iteration order is determined by hash codes and internal bucket placement, which c...

Read full answer

23. Why doesn't HashMap implement SequencedMap?

The same reasoning applies to maps as to sets: SequencedMap promises a defined encounter order for its entries, and HashMap 's iteration order depends on hash bucket layout rather than any guaranteed sequence. Adding firstEntry() / lastEntry() to HashMap would technically compile, but the "first"...

Read full answer

24. How does SequencedSet differ from a plain LinkedHashSet used before Java 21?

LinkedHashSet itself hasn't changed - it still maintains insertion order the same way it always has. What changed in Java 21 is that it now also implements SequencedSet , gaining a set of standard methods it didn't previously expose. Before Java 21 Java 21 onward No getFirst() / getLast() ; neede...

Read full answer

25. How does TreeSet implement SequencedSet given its natural ordering?

TreeSet doesn't implement SequencedSet directly in its own declaration - it implements NavigableSet , and as part of JEP 431, NavigableSet itself was retrofitted to extend SequencedSet . This works cleanly because TreeSet already had a well-defined order (natural ordering, or a supplied Comparato...

Read full answer

26. How does TreeMap support SequencedMap given its comparator-based ordering?

Like TreeSet , TreeMap supports SequencedMap indirectly - it implements NavigableMap , and JEP 431 retrofitted NavigableMap to extend SequencedMap . TreeMap already maintained entries in sorted order (natural ordering of keys, or via a supplied Comparator ) and already had equivalent operations s...

Read full answer

27. What is the difference between SequencedCollection and List?

SequencedCollection is a broader, more general interface that any collection with a defined encounter order can implement, while List is one specific, richer kind of ordered collection that happens to extend it. SequencedCollection List Defines only first/last access and reversal Adds full index-...

Read full answer

28. What is the difference between SequencedSet and NavigableSet?

SequencedSet is the more general interface, guaranteeing only that the set has some defined encounter order and exposing first/last/reversed operations for it. NavigableSet extends SequencedSet and adds much richer, sorted-order-specific navigation - methods like ceiling(e) , floor(e) , higher(e)...

Read full answer

29. What is the difference between List.reversed() and Collections.reverse()?

list.reversed() , new in Java 21, returns a fresh reverse-ordered view of the list and leaves the original list's own order completely untouched. Collections.reverse(list) , which has existed since Java 1.2, mutates the list in place, physically swapping elements so the original list itself ends ...

Read full answer

30. What is the difference between removeFirst()/removeLast() on SequencedCollection and on Deque?

Structurally, they're the same method signatures - Deque already had removeFirst() and removeLast() long before Java 21, and JEP 431 simply promoted them to the new, more general SequencedCollection interface. The practical difference is scope: on Deque , these methods were only ever guaranteed t...

Read full answer

31. When should you choose SequencedMap over a regular Map?

Reach for SequencedMap - or code against it as the declared type - whenever the order entries were inserted (or the order they end up sorted in) genuinely matters to your logic, not just their key-value association. Good fits include building a simple LRU-style cache with putFirst() / putLast() t...

Read full answer

32. When would you choose getFirst() over get(0) on a List?

Choose getFirst() whenever you're writing code that should read clearly and work uniformly across any SequencedCollection , not just lists - it says "give me the first element" without hardcoding an assumption about indexing. get(0) only exists on List , so code that uses it can never be generali...

Read full answer

33. What happens when you call getFirst() on an empty SequencedCollection?

It throws a NoSuchElementException , the same exception Deque.getFirst() and Deque.getLast() have always thrown when called on an empty deque. List empty = new ArrayList<>(); empty.getFirst(); // throws NoSuchElementException This is different from methods like peekFirst() on Deque , whic...

Read full answer

34. What happens when you call reversed() on an immutable List returned by List.of()?

It works fine and returns a reverse-ordered view - reversed() is a read operation, so it's fully supported even on immutable lists, since flipping the read direction doesn't require modifying the underlying list. List frozen = List.of(1, 2, 3); List rev = frozen.reversed(); // [...

Read full answer

35. What happens when you modify the original collection after calling reversed() on it?

Because reversed() returns a live view rather than a copy, any structural change to the original mutable collection - adding, removing, or replacing elements - is immediately visible through the reversed view too. List < String > list = new ArrayList <> (List.of( "a" , "b" )); List < String > rev...

Read full answer

36. How is the encounter order of a LinkedHashSet determined when using SequencedSet methods?

A LinkedHashSet 's encounter order is, by default, the order in which elements were inserted - the first element added (that's still present) is what getFirst() returns, and the most recently added element is what getLast() returns. LinkedHashSet < String > tags = new LinkedHashSet <> (); tags.ad...

Read full answer

37. How does LinkedHashMap's access-order mode interact with SequencedMap methods?

A LinkedHashMap can be constructed with accessOrder = true , which changes its encounter order so that reading an entry via get() moves it to the end, rather than leaving the order fixed at insertion time. LinkedHashMap cache = new LinkedHashMap<>(16, 0.75f, true); // access-orde...

Read full answer

38. Why doesn't Set.of() return a SequencedSet?

The immutable set returned by Set.of(...) deliberately has an unspecified iteration order - the JDK documentation for these factory methods explicitly states the order may vary between runs and even between calls with the same elements. This is intentional: Set.of(...) sometimes randomizes iterat...

Read full answer

39. Which is better and why: getFirst() or peekFirst() on an ArrayDeque?

Neither is universally "better" - they differ in how they handle an empty deque, so the right choice depends on whether an empty deque is an expected, normal case or a bug you want to surface loudly. getFirst() peekFirst() Throws NoSuchElementException if empty Returns null if empty Good when an ...

Read full answer

40. How can you optimize iteration and access using SequencedCollection methods instead of manual indexing?

Using getFirst() / getLast() instead of manual index math doesn't change the algorithmic complexity for something like ArrayList - both are O(1) - but it does eliminate an entire class of off-by-one bugs from re-deriving size() - 1 everywhere. The bigger optimization opportunity is on collections...

Read full answer

41. How can you optimize a producer-consumer pattern using ArrayDeque's sequenced methods?

ArrayDeque already supported first/last operations before Java 21, so what changes is mainly that this same producer-consumer pattern can now be written against the general SequencedCollection interface, making the code reusable across other sequenced types too. SequencedCollection queue = ...

Read full answer

42. How do you troubleshoot a NoSuchElementException thrown from a sequenced collection method?

This exception means getFirst() , getLast() , removeFirst() , or removeLast() was called on a collection that turned out to be empty at that moment - the fix is almost always to check for emptiness before calling one of these methods, not to catch the exception after the fact. Start by checking w...

Read full answer

43. How do you troubleshoot UnsupportedOperationException when calling addFirst() on an unmodifiable list?

This exception means the list you're calling addFirst() on doesn't support structural modification - commonly a list created with List.of(...) , Collections.unmodifiableList(...) , or the fixed-size list returned by Arrays.asList(...) . List frozen = List.of("a", "b"); frozen.addFirst("z"...

Read full answer

44. Explain the internal working of the reversed() view for a List?

reversed() does not copy elements or allocate a new backing array; it returns a lightweight wrapper object that delegates every call back to the original list, translating indexes as it goes. Internally, a call like reversedList.get(i) is translated to originalList.get(size - 1 - i) on the underl...

Read full answer

45. Explain the lifecycle of a view returned by SequencedMap.reversed()?

When you call reversed() on a SequencedMap , the JDK constructs a new, lightweight SequencedMap wrapper object whose lifetime is tied entirely to the original map - it holds a reference back to it rather than copying any entries. flowchart TD A["map.reversed() called"] --> B["New reversed-view ob...

Read full answer

46. Explain the execution flow of putFirst() on a LinkedHashMap?

Internally, LinkedHashMap maintains a doubly linked list threaded through its entries in addition to the usual hash table, and that linked list is what actually defines the map's encounter order. sequenceDiagram participant Caller participant LinkedHashMap participant HashTable participant Linked...

Read full answer

47. Explain the internal working of the retrofit strategy used to add Sequenced interfaces without breaking existing implementations?

The JDK team's core constraint was strict backward compatibility: millions of existing classes implement List , Deque , Set , and Map , and none of them could be forced to suddenly implement new methods they know nothing about. The solution was to insert the new interfaces into the existing hiera...

Read full answer

48. Why is Deque now classified as a SequencedCollection?

Deque already had exactly the semantics SequencedCollection was designed to generalize: elements at two distinguishable ends, first and last, with methods to add, read, and remove from either end. Making Deque extend SequencedCollection meant the JDK could remove duplication rather than add it - ...

Read full answer

49. What is the difference between SequencedCollection and the Queue interface?

SequencedCollection and Queue both deal with ordered access, but they model different things: SequencedCollection is about having elements arranged with a defined first-to-last order and being able to reach either end, while Queue is specifically about FIFO-style processing semantics. SequencedCo...

Read full answer

50. Explain how record patterns in Java 21 complement processing elements of sequenced collections?

Record patterns (JEP 440) and pattern matching for switch (JEP 441) are separate features from Sequenced Collections (JEP 431), but Java 21 finalized all three together, and they combine naturally when the elements stored inside a sequenced collection are themselves records. record Point(int x, i...

Read full answer

«
»

Comments & Discussions