tree set – Programmerbay https://programmerbay.com A Tech Bay for Tech Savvy Tue, 11 Jul 2023 17:20:12 +0000 en-US hourly 1 https://wordpress.org/?v=6.5.5 https://programmerbay.com/wp-content/uploads/2019/09/cropped-without-transparent-32x32.jpg tree set – Programmerbay https://programmerbay.com 32 32 SortedSet Interface in Java With Program Example https://programmerbay.com/sortedset-interface-in-java-with-program-example/ https://programmerbay.com/sortedset-interface-in-java-with-program-example/#respond Tue, 11 Jul 2023 17:19:23 +0000 https://programmerbay.com/?p=9389

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

]]>
https://programmerbay.com/sortedset-interface-in-java-with-program-example/feed/ 0