Java SortedSet Interface

https://‮igi.www‬ftidea.com

In Java, the SortedSet interface is a subinterface of the Set interface that provides a total ordering on the elements of the set. This means that the elements in a SortedSet are arranged in a specific order defined by a comparator or by the natural ordering of the elements. A SortedSet does not allow null elements.

The SortedSet interface provides the following methods, in addition to those provided by the Set interface:

  • comparator(): Returns the comparator used to order the elements in the set, or null if the natural ordering is used.
  • first(): Returns the first (lowest) element in the set.
  • last(): Returns the last (highest) element in the set.
  • headSet(toElement): Returns a view of the portion of the set whose elements are strictly less than toElement.
  • tailSet(fromElement): Returns a view of the portion of the set whose elements are greater than or equal to fromElement.
  • subSet(fromElement, toElement): Returns a view of the portion of the set whose elements are greater than or equal to fromElement and strictly less than toElement.

Here is an example of how to use the SortedSet interface in Java:

import java.util.SortedSet;
import java.util.TreeSet;

public class SortedSetExample {
    public static void main(String[] args) {
        // Create a new TreeSet
        SortedSet<Integer> set = new TreeSet<>();

        // Add elements to the set
        set.add(3);
        set.add(1);
        set.add(2);

        // Print the set
        System.out.println(set);

        // Print the first and last elements of the set
        System.out.println("First element: " + set.first());
        System.out.println("Last element: " + set.last());

        // Print a view of the set from 1 (inclusive) to 3 (exclusive)
        System.out.println("Subset: " + set.subSet(1, 3));
    }
}

Output:

[1, 2, 3]
First element: 1
Last element: 3
Subset: [1, 2]

In the example above, we have created a TreeSet of integers, which implements the SortedSet interface. We have added three elements to the set, which are automatically sorted in ascending order. We have then printed the set, which shows the elements in the sorted order. We have also printed the first and last elements of the set using the first() and last() methods. Finally, we have printed a view of the set using the subSet() method, which returns a subset of the set whose elements are greater than or equal to 1 and strictly less than 3.