Java / Java 21 Collection Framework features Interview questions
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, int y) {} List<Point> path = new ArrayList<>(List.of(new Point(0, 0), new Point(3, 4))); Point last = path.getLast(); String description = switch (last) { case Point(int x, int y) when x == 0 && y == 0 -> "origin"; case Point(int x, int y) -> "at (" + x + ", " + y + ")"; };
Here, getLast() handles retrieving the element from the sequenced collection cleanly, while the record pattern in the switch destructures that element's components directly, without a chain of separate .x() and .y() accessor calls.
Iterating a reversed() view works the same way - each element pulled from the reversed encounter order can still be matched and destructured with a record pattern, since reversed() only changes traversal order, not the type or structure of the elements themselves.
So the two features are complementary rather than dependent: Sequenced Collections standardizes how you navigate to an element, and record patterns standardize how you pull that element's data apart once you have it - together they reduce boilerplate at both the collection-access layer and the data-extraction layer.
More Related questions...