![]() |
VOOZH | about |
The SortedSet interface is present in java.util package that extends the Set interface, which maintains unique elements in sorted order, either by natural ordering or a custom comparator.
Since SortedSet is an interface, objects cannot be created directly. Use a class like TreeSet that implements it.
public interface SortedSet<E> extends Set<E>
[10, 20, 40, 50] First element: 10 Last element: 50
Explanation:
SortedSet interface extends the Set interface.
To add elements to a SortedSet, use the add() method.In a TreeSet, elements are automatically sorted in ascending order, duplicates are ignored, and null values are not allowed.
[A, B, C]
We can access elements using methods such as contains(), first(), last(), etc.
Sorted Set is: [A, B, C] Contains: D false First Value: A Last Value: C
The values can be removed from the SortedSet using the remove() method.
Initial TreeSet: [A, B, C, D, E] After removing element: [A, C, D, E]
There are various ways to iterate through the SortedSet. The most famous one is to use the enhanced for loop.
A, B, C, D, E, Z,
Note: The class which implements the SortedSet interface is TreeSet.
The following are the methods present in the SortedSet interface. Here, the “*” represents that the methods are part of the Set interface.
| Method | Description |
|---|---|
| add(element) | Adds an element if not already present. |
| addAll(collection) | Adds all elements from another collection. |
| clear() | Removes all elements (set remains empty). |
| comparator() | This method returns the comparator used to order the elements in this set. |
| contains(element) | This method is used to check whether a specific element is present in the Set or not. |
| containsAll(collection) | Checks if all elements of a collection are in the set. |
| first() | This method returns the first(lowest) element present in this set. |
| hashCode() | Returns the hash code of the set. |
| headSet(element) | This method returns the elements which are less than the element that are present in the sorted set. |
| isEmpty() | This method is used to check if a SortedSet is empty or not. |
| last() | This method returns the last(highest) element present in the set. |
| remove(element) | Removes the given element |
| removeAll(collection) | Removes all matching elements from the set. |
| retainAll(collection) | Keeps only elements present in the given collection. |
| size() | Returns the number of elements in the set. |
| subSet(element1, element2) | This method returns a sorted subset from the set containing the elements between element1 and element2. |
| tailSet(element) | This method returns the elements which are greater than or equal to the element that are present in the sorted set. |
| toArray() | This method is used to form an array of the same elements as that of the Set. |