SortedSet Interface in Java With Program Example

SortedSet is an interface whose implementation class is TreeSet. With the help of implementation classes, we can assign its instance to sortedSet interface. Below is the example:

Program:

import java.util.*;

public class SetExample {
    public static void main(String[] args) {
        SortedSet<String> sortedSet = new TreeSet<>() ;  // Creating sortedSet object

        // Adding elements to sorted set object
        sortedSet.add("Example");
        sortedSet.add("Code");
        sortedSet.add("A");

        // Displaying the output
        System.out.println(sortedSet);

        // Removing A element from the set
        sortedSet.remove("A");

        System.out.println(sortedSet);

        // printing first element from the set
        System.out.println(sortedSet.first());

        // printing last element from the set
        System.out.println(sortedSet.last());
    }
}

Output:

[A, Code, Example]
[Code, Example]
Code
Example

Methods of SortSet Interface

Existing methods from Set interface
Method NameExplanation
add(Object)The method adds an element in a given set, returns false if one tries to add duplicate element
addAll(CollectionObj)It adds all the elements of the given collection in a given set
clear()It removes all elements from the given set
contains(Object)It checks whether the given object consists in a set or not, if it returns true if exist, otherwise false
containsAll(CollectionObj)It returns true, if all the elements of the given collection exist in the set, otherwise false
isEmpty()It checks whether a set is empty or not. it returns if empty, other false
iterator()It provides iterator object to iterate through set
remove(Object)It removes the given object from the set, if present
retainAll(CollectionObj)It retains elements of the collection provided in the method, and removed all other elements in the set that don't match the elements of collection object
size()It returns number of elements present in a set
spliterator()it returns spliterator object to iterate through set
toArray()It converts given set and returns array
removeAll(CollectionObj)It removes all the elements consisting in the collection object

Leave a Reply