Introduction
The SortedSet interface extends the Set Interface, which I already discussed in my Previous Article. The elements of this interface are sorted in ascending order. Iterators are similar to Enumeration. Iterators allow the user to remove elements from the current collection during the iteration with well-defined semantics, whereas Enumeration does not allow such removal.
SortedSet Interface
public interface SortedSet<E> extends Set<E>
Key Characteristics
- Maintains elements in ascending order.
- Doesn’t allow duplicate entries.
- Can define custom sorting using a Comparator.
Methods used in the SortedSet Interface
Methods |
Description |
Comparator comparator() |
Returns the comparator of the current sorted set. It returns null if the natural ordering is used for the set. |
Object first() |
Returns the first element of the current sorted set. |
SortedSet headset(Object a) |
Returns a SortedSet that contains elements less than the object a from the current sorted set. |
Object last() |
Returns the last element of the current sorted set |
SortedSet subSet(Object a, Object b) |
Returns a SortedSet containing elements between the object a and the object b. |
SortedSet tailSet(Object a) |
Returns a SortedSet containing elements greater than or equal to a from the current sorted set. |
The methods of the SortedSet Interface can be divided into three categories. They are
- Range-view operations
- Endpoint operations
- Comparator Accessor
Range-View Operations
Range-view operations perform arbitrary range operations over the sorted set. The range view of a sorted set remains valid even if the original sorted set is modified directly. This is because the range-view of a sorted set is a window of a portion of the set that lies in the designated part of the element-space. Any change to the range-view is written back to the original sorted set and vice versa. The methods subset, headset, and tailSet are the Range-view operations of the sorted set. Assume that we want to find the number of words between “alpha” and “gamma” in a sorted set of strings called stringSet. The subset method can be used for this purpose as below:
int count=stringSet.subset(“alpha”,”gamma”).size()
The search includes alpha but excludes gamma while searching. If we want to exclude both words while searching, then the code statement given above should be modified as follows:
int count=stringSet.subset(“alpha\0”,”gamma”).size()
On the other hand, in order to include both words in the search, we give the code statement as shown below:
int count=stringSet.subsset(“alpha”,gamma\0”).size()
The headset method is used to view the sorted set from the beginning up to the specified object. For instance, if we need to view all the words up to “gamma” from the sorted set named stringSet, we should use the following code statement.
SortedSet s1=stringSet.headSet(“gamma”);
The tailSet method is used to view the sorted set starting from the specified object up to the end of the sorted set. For instance, if we need to view all the words starting with “gamma” from the sorted set stringSet, we should use the following code statement
SortedSet s1=stringSet.tailSet(“gamma”);
Source Code
import java.util.*;
public class SortedSetExample {
public static void main(String[] args) {
SortedSet<String> stringSet = new TreeSet<>();
stringSet.add("alpha");
stringSet.add("beta");
stringSet.add("delta");
stringSet.add("gamma");
stringSet.add("epsilon");
System.out.println("Original Set: " + stringSet);
SortedSet<String> sub = stringSet.subSet("alpha", "gamma");
System.out.println("Subset (alpha to gamma): " + sub);
SortedSet<String> head = stringSet.headSet("gamma");
System.out.println("HeadSet (before gamma): " + head);
SortedSet<String> tail = stringSet.tailSet("gamma");
System.out.println("TailSet (from gamma): " + tail);
}
}
Output
![Command prompt]()
Endpoint operations
The Endpoint operations, namely, the first and last methods, are used to return the first and last elements of the sorted set. These methods can be used in combination with the range-view operations to get the desired result. For instance, if we need the first word in the sorted set that is less than the word “gamma”, we should use the following code statement
String s=stringSet.headSet(“gamma”)last()
Comparator Accessor
The comparator method of this interface is in the comparator accessor that returns the comparator used to sort the set. If the set is sorted according to the natural order of its elements, then the method returns null.
Check if a custom comparator is used:
Comparator comp = stringSet.comparator();
if (comp == null)
System.out.println("Using natural ordering");
Iterator Interface
Iterators are similar to Enumeration, except for two differences between them. Iterators allow the user to remove elements from the current collection during the iteration with well-defined semantics, whereas Enumeration does not allow such removal. Method names have been improved in Iterations as compared to Enumeration.
public interface Iterator<E>
Methods used in the Iterator Interface
Returns the next element in the iteration. If the iteration has no more elements, then it throws the NoSuchElementException.
Methods |
Description |
Booelan hasNext() |
If the iteration has more elements, then it returns true, else it returns false. |
Object next() |
void remove() |
Removes the last element returned by the iterator from the current collection. It can be called only once per call to the next method. |
Source Code
import java.util.*;
public class IteratorExample {
public static void main(String[] args) {
Set<String> languages = new HashSet<>();
languages.add("Java");
languages.add("Python");
languages.add("C++");
Iterator<String> it = languages.iterator();
while (it.hasNext()) {
String lang = it.next();
System.out.println(lang);
if (lang.equals("Python")) {
it.remove();
}
}
System.out.println("After removal: " + languages);
}
}
Output
![Command prompt]()
Summary
The SortedSet interface in Java extends the Set interface and stores elements in ascending order, either by natural ordering or a custom comparator. It supports operations like subSet(), headSet(), and tailSet() for range-based data access. Methods like first() and last() help fetch boundary elements, while comparator() checks the sorting mechanism.
The Iterator interface enables traversal over collections with support for safe removal of elements during iteration. Unlike Enumeration, it provides better flexibility and modern method naming. Core methods include hasNext(), next(), and remove().