Java SortedSet Interface


In Java, the SortedSet interface is a part of the java.util package and extends the Set interface. It represents a set of elements that are stored in a sorted order. This means that the elements in a SortedSet are automatically ordered, either by their natural ordering (using Comparable) or by a Comparator provided at the time of creation.


What is Java SortedSet?

The SortedSet interface is an extension of the Set interface. It guarantees that the elements within the set are sorted according to their natural order (or by a Comparator if one is provided). It offers additional methods compared to Set, allowing you to retrieve elements in a specific range or order.

Key Features of SortedSet:

  • Sorted Elements: Elements are maintained in sorted order.
  • No Duplicates: Like all Set implementations, SortedSet does not allow duplicate elements.
  • Natural Order or Comparator: The ordering can either be natural (using Comparable) or defined by a Comparator.
  • Navigation: You can easily navigate through the set to find elements in a specified range or order.

Core Methods in SortedSet

The SortedSet interface introduces several useful methods for working with sorted elements. Here are some of the key methods:

1. first()

Returns the first (lowest) element in the set.

E first();

2. last()

Returns the last (highest) element in the set.

E last();

3. headSet(E toElement)

Returns a view of the portion of the set whose elements are strictly less than toElement.

SortedSet<E> headSet(E toElement);

4. tailSet(E fromElement)

Returns a view of the portion of the set whose elements are greater than or equal to fromElement.

SortedSet<E> tailSet(E fromElement);

5. subSet(E fromElement, E toElement)

Returns a view of the portion of the set whose elements are greater than or equal to fromElement and less than toElement.

SortedSet<E> subSet(E fromElement, E toElement);

6. comparator()

Returns the comparator used to order the elements in the set, or null if the set uses the natural ordering of the elements.

Comparator<? super E> comparator();

Implementations of SortedSet

The SortedSet interface has several implementations in Java, with TreeSet being the most commonly used.

TreeSet:

The TreeSet class is the primary implementation of the SortedSet interface in Java. It stores elements in a balanced tree structure, ensuring that the elements are sorted in natural order or according to a custom comparator.

Example of using TreeSet with SortedSet:

import java.util.*;

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

        // Add elements to the set
        sortedSet.add("Banana");
        sortedSet.add("Apple");
        sortedSet.add("Orange");
        sortedSet.add("Grape");

        // Display the elements (sorted in natural order)
        System.out.println("SortedSet elements: " + sortedSet);

        // Get the first and last elements
        System.out.println("First element: " + sortedSet.first());
        System.out.println("Last element: " + sortedSet.last());

        // Get a subset from the set
        SortedSet<String> headSet = sortedSet.headSet("Orange");
        System.out.println("HeadSet (less than 'Orange'): " + headSet);

        SortedSet<String> tailSet = sortedSet.tailSet("Orange");
        System.out.println("TailSet (greater than or equal to 'Orange'): " + tailSet);

        SortedSet<String> subSet = sortedSet.subSet("Apple", "Grape");
        System.out.println("SubSet (from 'Apple' to 'Grape'): " + subSet);
    }
}

Output:

SortedSet elements: [Apple, Banana, Grape, Orange]
First element: Apple
Last element: Orange
HeadSet (less than 'Orange'): [Apple, Banana, Grape]
TailSet (greater than or equal to 'Orange'): [Orange]
SubSet (from 'Apple' to 'Grape'): [Apple, Banana]

Explanation:

  • first() returns the first (lowest) element in the set.
  • last() returns the last (highest) element in the set.
  • headSet("Orange") returns a subset containing elements strictly less than Orange.
  • tailSet("Orange") returns a subset containing elements greater than or equal to Orange.
  • subSet("Apple", "Grape") returns a subset containing elements from Apple to Grape (excluding Grape).

Advantages of Using SortedSet

  1. Sorted Order: SortedSet ensures that elements are always sorted, either by their natural order or by a custom comparator.
  2. Efficient Range Queries: It provides methods to retrieve subsets of elements, allowing you to efficiently query elements within a specific range.
  3. Navigation Methods: SortedSet offers several useful navigation methods such as first(), last(), headSet(), and tailSet(), making it easy to retrieve specific elements or subsets.

When to Use SortedSet

Consider using SortedSet when:

  1. You Need Sorted Elements: If you need to store elements that should always be sorted, such as in a priority queue or when you need to maintain an ordered collection.
  2. Efficient Range Operations: If you need to perform operations on subsets of elements based on their order (such as filtering elements within a specific range).
  3. Navigating Ordered Data: When you need to access the first, last, or specific ranges of elements in a sorted collection.

SortedSet vs Set

Feature SortedSet Set
Ordering Elements are sorted. No specific order.
Additional Methods Methods like first(), last(), headSet(), tailSet(). No additional methods for order navigation.
Use Case When sorted order is needed. When order does not matter.