Last Updated: 07 July, 2023
SortedSet is an interface in the Java Collections Framework that extends the Set interface. Sorted was introduced in the JDK 1.2 version and is available in the java.util package.
It maintains a collection of elements in ascending order, sorted according to the elements' natural ordering or according to a Comparator provided at SortedSet creation time.
SortedSet declaration:
Here, E defines the type of elements that the Set will contain.
The SortedSet interface can be implemented by the following classes in Java:
Here's an example of how to use SortedSet in Java:
Output
Sorted Set: [1, 2, 4, 5, 8]
Ascending Order: 1 2 4 5 8
First Element: 1
Last Element: 8
Sorted Set after removal: [1, 4, 5, 8]
In the example above, we create a TreeSet, which is a commonly used implementation of SortedSet. We add some integers to the set, and they are automatically sorted in ascending order. We can iterate over the set in ascending order using a for-each loop. We can also retrieve the first and last elements of the set using the first() and last() methods. Finally, we remove an element from the set using the remove() method, and the set is updated accordingly.
Reference: https://docs.oracle.com/en/java/javase/11/docs/api/java.base/java/util/SortedSet.html
That's all guys, hope this Java article is helpful for you.
Happy Learning... 😀
feedback@javabytechie.com