Here is an example of accessing the First and Last Element in Java 21:
Prior to JDK 21, retrieving the first and last elements of collections in Java involved different methods and approaches depending on the collection type. Let’s examine some examples of accessing the first and last elements using the pre-JDK 21 JDK API calls:
For List:
First Element: list.get(0)
Last Element: list.get(list.size()-1)
For Deque:
First Element: deque.getFirst()
Last Element: deque.getLast()
For Set:
First Element: set.iterator().next() or set.stream().findFirst().get()
Last Element: requires iterating through the set
For SortedSet:
First Element: set.first()
Last Element: set.last()
With the introduction of JDK 21 and the Sequenced Collections feature, accessing the first and last elements becomes more consistent and straightforward. The new methods simplify the process across different collection types:
For List, Deque, Set:
First Element: collection.getFirst()
Last Element: collection.getLast()