New Features in java 21
Introduction
Java 21 New Features | Java 21 will be released on September 2023, and it will be a LTS release. LTS is a Long Term Support release by oracle, for which oracle will provide long term support for extended period over the regular one. As of today, what we know so far is that java 21 will add Sequenced Collections – JEP 431.
Sequenced Collections
What is sequenced collections in java 21?
Java 21 introduce sequenced collection, which is a collection whose elements have a defined encounter order (referred to as sequenced – arrange elements in a particular order). A sequenced collection has first and last elements, and the elements between them have successors and predecessors.
Sequenced collection supports processing elements from forward and reverse order.
The Problem, Why we need Sequenced Collections ?
Every collection in java has the order called encounter order, which means that elements in that collection has a well-defined order and iteration will happen on that order, but this is true for sorted collections like sortedSet, all lists as they are sequenced. But what about non-sequential collections without encounter order like a HashSet.
Sequence related operations are inconsistent. e.g. to get first element of list is easy like
List<Employee> employeeList....
employeeList.get(0); // get the first element of the list.
employeeList.get(0); will give you the first element, but getting the last element is a pain as we need to write:
List<Employee> employeeList....
employeeList.get(0); // get the first element of the list.
employeeList.get(employeeList.size()-1); // last element from the list.
Similarly, for LinkedHashSet getting first element from set:
set.iterator().next()
set.stream().findFirst()
For getting last element from set is not possible without iteration. Not just last to get any element from set we need to stream on it.
Similarly, to reverse the collection, we don’t have any method. The solution is nothing but sequenced collections, as it has these methods:
interface SequencedCollection<E> extends Collection<E> {
// new method
SequencedCollection<E> reversed();
// methods promoted from Deque
void addFirst(E);
void addLast(E);
E getFirst();
E getLast();
E removeFirst();
E removeLast();
}
Methods():
void addFirst(E)
void addLast(E)
E getFirst()
E getLast()
E removeFirst()
E removeLast()
//source openJDK JEP-431
These are the updates on java 21 as of now, will update more as they are released.
See more Java 17 New Features here..