SortedSet subSet() method in Java

The subSet() method in Java is located within the SortedSet interface, and it is a part of the Set interface, and each element in the collection is sorted as per defined order. The SortedSet interface allows the iterators to traverse the elements in the ascending order that strictly follow the natural ordering of the elements or are directed by a provided Comparator.

The subSet() method is used to visualize a portion of the sorted set, determined by a specified range of the values. It yields a subsection, consisting of the elements, larger than or equal to a specified fromElement and smaller than a specified toElement of the original sorted set.

Method Signature

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

 SortedSet: It mentions the return type of the method. The message signifies that the subSet() method will return a SortedSet containing elements of the type E. SortedSet is an interface in Java's collections framework which extends the Set interface to represent a collection of elements maintained in a specific order.

subSet: It is the name of the method. It denotes that this method is used to obtain a subset of the sorted set.

<E>: It indicates that the method is generic, with the type parameter E representing the type of elements in the sorted set and the subset.

fromElement: It is the first parameter of the method, representing the lowest element (inclusive) in the subset. It specifies the starting point of the range for creating the subset.

toElement: It is the second parameter of the method, representing the highest element (exclusive) in the subset. It specifies the ending point of the range for creating the subset.

Various examples using SortedSet subset method

1. Using TreeSet to create subsets based on ranges

    The TreeSet class in Java provides a method called subSet() which allows us to obtain a view of a portion of the sorted set, defined by a specified range. This method takes two parameters: fromElement (inclusive) and toElement (exclusive). It returns a subset of the original sorted set that contains elements greater than or equal to fromElement and strictly less than toElement.

    Algorithm

    Step 1: Import necessary classes from the java.util package, including SortedSet and TreeSet, which are used to work with sorted sets in Java.

    Step 2: Class Declaration: The class SubSetExample is to be declared, which contains the main() method.

    Step 3: Creating TreeSet: A TreeSet named set should be created to store integers. TreeSet is a sorted set, so the elements will be automatically sorted in ascending order.

    Step 4: Adding Elements to TreeSet: Integers 10, 20, 30, 40, and 50 are added to the set.

    Step 5: Creating Subsets: Three subsets (subset1, subset2, and subset3) are created using the subSet() method of the set. Each subset is created based on a different range of values.

    Step 5.1: subset1 contains elements greater than or equal to 20 and less than 40. subset2 contains elements greater than or equal to 30 and less than 50. subset3 contains elements greater than or equal to 15 and less than 35.

    Step 6: Printing Subsets: The subsets are printed and each subset is printed along with its contents.

    Filename: SubSetExample.java

    import java.util.*;

    public class SubSetExample {

        public static void main(String[] args) {

            // Create a TreeSet containing integers

            SortedSet<Integer> set = new TreeSet<>();

            set.add(10);

            set.add(20);

            set.add(30);

            set.add(40);

            set.add(50);

            // Create subsets based on different ranges

            SortedSet<Integer> subset1 = set.subSet(20, 40);  // Subset containing elements >= 20 and < 40

            SortedSet<Integer> subset2 = set.subSet(30, 50);  // Subset containing elements >= 30 and < 50

            SortedSet<Integer> subset3 = set.subSet(15, 35);  // Subset containing elements >= 15 and < 35

            // Print subsets

            System.out.println("Subset 1: " + subset1); // Output: Subset 1: [20, 30]

            System.out.println("Subset 2: " + subset2); // Output: Subset 2: [30, 40]

            System.out.println("Subset 3: " + subset3); // Output: Subset 3: [20, 30]

        }

    }

    Output:

    Subset 1: [20, 30]

    Subset 2: [30, 40]

    Subset 3: [20, 30]

    2.Using custom objects and a comparator to create subsets

    The SortedSet interface in Java extends the Set interface to represent a collection of elements sorted in a specific order. The subSet() method in SortedSet allows you to obtain a view of a portion of the sorted set defined by a specified range. By providing a custom comparator, you can define the sorting criteria for the objects in the set.

    Algorithm

    Step 1: Define a custom class named Person with two fields: name and age. Implement a constructor to initialize these fields.

    Step 2: Implement getter methods to access the name and age fields. Override the toString() method to provide a string representation of the Person object.

    Step 3: Create a comparator for Person objects based on their age property using Comparator.comparingInt().

    Step 4: Create a TreeSet named set to store Person objects, using the comparator created in the previous step to ensure sorting by age.

    Step 5: Add Persons to the TreeSet: Add several Person objects to the set, each with varying ages and use the subSet() method of the SortedSet interface to create a subset of Person objects aged between 25 and 30.

    Step 6: Pass new Person("", 25) (inclusive) and new Person("", 31) (exclusive) as arguments to specify the range. Print the subset containing people aged between 25 and 30.

    Filename: SubSetExample.java

    import java.util.*;

    // Custom class representing a Person

    class Person {

        private String name;

        private int age;

        public Person(String name, int age) {

            this.name = name;

            this.age = age;

        }

        public String getName() {

            return name;

        }

        public int getAge() {

            return age;

        }

        @Override

        public String toString() {

            return name + " (" + age + ")";

        }

    }

    public class SubSetExample {

        public static void main(String[] args) {

            // Create a TreeSet containing Person objects sorted by age

            SortedSet<Person> set = new TreeSet<>(Comparator.comparingInt(Person::getAge));

            set.add(new Person("Alice", 25));

            set.add(new Person("Bob", 30));

            set.add(new Person("Charlie", 20));

            set.add(new Person("David", 35));

            set.add(new Person("Emily", 28));

            // Create a subset of people aged between 25 and 30

            SortedSet<Person> subset = set.subSet(new Person("", 25), new Person("", 31));

            // Print the subset

            System.out.println("Subset of people aged between 25 and 30: " + subset);

        }

    }

    Output:

    Subset of people aged between 25 and 30: [Alice (25), Emily (28), Bob (30)] 

                           

    3. Modifying the original set

    When we create a subset using the subSet() method of a SortedSet, we can obtain a view of a portion of the original set, this view is backed by the original set, meaning changes made to either the original set or its subsets are reflected in each other. Therefore, modifying the original set can affect its subsets, and modifying a subset can affect the original set.

    Algorithm

    Step 1: Create a SortedSet named set, add integers 10, 20, 30, 40, and 50 to the set.

    Step 2: Create a Subset: Use the subSet() method of the SortedSet interface to create a subset named subset containing elements greater than or equal to 20 and strictly less than 40.

    Step 3: Print the contents of the original set (set) and the subset (subset) to observe their initial state.

    Step 4: Modify the Original Set: Remove the element 30 from the original set (set) using the remove() method.

    Step 5: Add the element 35 to the original set (set) using the add() method. Print the contents of the modified original set (set) and the subset (subset) to observe the changes.

    Filename: SubSetExample1.java

    import java.util.*;

    public class SubSetExample1 {

        public static void main(String[] args) {

            // Create a TreeSet containing integers

            SortedSet<Integer> set = new TreeSet<>();

            set.add(10);

            set.add(20);

            set.add(30);

            set.add(40);

            set.add(50);

            // Create a subset

            SortedSet<Integer> subset = set.subSet(20, 40);

            // Print original set and subset

            System.out.println("Original Set: " + set);

            System.out.println("Subset: " + subset);

            // Modify the original set

            set.remove(30);

            set.add(35);

            // Print modified original set and subset

            System.out.println("Modified Original Set: " + set);

            System.out.println("Subset after modification: " + subset);

        }

    }

    Output:

    Original Set: [10, 20, 30, 40, 50]

    Subset: [20, 30]

    Modified Original Set: [10, 20, 35, 40, 50]

    Subset after modification: [20, 35]

    Conclusion

    The subSet() method in Java's SortedSet interface offers a convenient and efficient way to work with subsets of sorted data. The subSet() method allows us to create subsets of a sorted set based on defined ranges, providing flexibility in selecting specific portions of the data. Its ability to create views of the original set while maintaining consistency between subsets and the original set makes it a valuable tool for various applications, from data manipulation to algorithm design. However, we should be mindful of its behavior, especially when modifying the original set or its subsets, to ensure correct and predictable outcomes.