Sequenced collections in Java

Java interview exercise on Modern Java, difficulty 1 of 3. Solve it in the editor beside a worked example; the tests run the moment you do.

Write static <T> List<T> firstAndLast(items) that returns a two-element list of the first and the last element of a List, using the Java 21 getFirst() and getLast() (which throw NoSuchElementException on an empty list, which is the behaviour to keep). A one-element list gives that element twice.

Each exercise pairs a worked example with a twin problem to solve in a real editor; the tests run the moment you do. Progress is saved in your browser, and in your account if you sign in.

More Modern Java in Java

All Java exercises · Other languages and frameworks