Java Set Interface

Java Setinterface

What is Java Set Interface?

Java Set Interface is a collection type that represents a group of unique elements with no specific order. It extends the Collection interface and doesn’t allow duplicate elements.

The Set interface provides various methods to manipulate elements such as add, remove, contains, and clear.Some popular Set implementations in Java include HashSet, TreeSet, and LinkedHashSet.

To understand the more about Java Set Interface, Read the Complete Article.

Classes that implement Set: 

In Java, several classes implement the Set interface. Here are some commonly used ones:

  • HashSet: It stores elements in a hash table and provides constant-time performance for adding, removing, and searching operations. However, it does not guarantee the order of elements.
  • TreeSet: It stores elements in a sorted tree structure and maintains elements in ascending order. It provides efficient operations for finding elements, but insertion and deletion take more time than HashSet.
  • LinkedHashSet: It maintains the order of insertion while still providing constant-time performance for add, remove, and search operations.
  • EnumSet: It is a specialized Set implementation used to store a set of enum constants.
Java Set Interface

Interfaces that extend Set:

Set Interfaces

Methods of PrintStream

MethodsDescription
add(E element):Adds the specified element to the set if it is not already present.
remove(Object obj):Removes the specified element from the set if it is present.
contains(Object obj):Returns true if the set contains the specified element.
size():Returns the number of elements in the set.
clear():Removes all elements from the set.
isEmpty(): Returns true if the set contains no elements.
iterator(): Returns an iterator over the elements in the set.
toArray(): Returns an array containing all of the elements in the set.

The Set interface extends the Collection interface, it also inherits methods such as addAll(), removeAll(), retainAll(), and containsAll() from the Collection interface.

Set Operations 

Set operations are a collection of mathematical operations that can be performed on sets. In Java, these operations can be performed using the methods provided by the Set interface.

Here are some of the commonly used set operations:

  • Union: The union of two sets is the set of all elements that are in either set. This can be achieved in Java by using the addAll() method.
  • Intersection: The intersection of two sets is the set of all elements that are in both sets. This can be achieved in Java by using the retainAll() method.
  • Subset: A set A is said to be a subset of set B if all elements of A are also elements of B. This can be achieved in Java by using the containsAll() method.
  • Disjoint: Two sets are said to be disjoint if they have no elements in common. This can be achieved in Java by checking if the intersection of the two sets is an empty set.
  • Difference: The difference of two sets is the set of all elements that are in the first set but not in the second set. This can be achieved in Java by using the removeAll() method.

Example 1: Java Program to Implementing HashSet Class

Run
import java.util.HashSet;

public class Main {
    public static void main(String[] args) {
        // Create a new HashSet
        HashSet set = new HashSet<>();

        // Add some elements to the HashSet
        set.add("apple");
        set.add("banana");
        set.add("orange");
        set.add("pear");

        // Print the contents of the HashSet
        System.out.println("HashSet contains: " + set);

        // Add a duplicate element
        set.add("apple");

        // Print the contents of the HashSet after adding duplicate
        System.out.println("HashSet contains: " + set);

        // Remove an element from the HashSet
        set.remove("orange");

        // Print the contents of the HashSet after removing element
        System.out.println("HashSet contains: " + set);

        // Check if the HashSet contains an element
        System.out.println("HashSet contains 'banana': " + set.contains("banana"));

        // Get the size of the HashSet
        System.out.println("Size of HashSet: " + set.size());

        // Clear the HashSet
        set.clear();

        // Print the contents of the HashSet after clearing
        System.out.println("HashSet contains: " + set);
    }
}

Output

HashSet contains: [banana, orange, apple, pear]
HashSet contains: [banana, orange, apple, pear]
HashSet contains: [banana, apple, pear]
HashSet contains 'banana': true
Size of HashSet: 3
HashSet contains: []

Example 2: Java Program to printf() method using PrintStream

 
Run
import java.util.TreeSet;
//TreeSetExample
public class Main {
    public static void main(String[] args) {
        // Create a new TreeSet
        TreeSet set = new TreeSet<>();

        // Add some elements to the TreeSet
        set.add("apple");
        set.add("banana");
        set.add("orange");
        set.add("pear");

        // Print the contents of the TreeSet
        System.out.println("TreeSet contains: " + set);

        // Add a duplicate element
        set.add("apple");

        // Print the contents of the TreeSet after adding duplicate
        System.out.println("TreeSet contains: " + set);

        // Remove an element from the TreeSet
        set.remove("orange");

        // Print the contents of the TreeSet after removing element
        System.out.println("TreeSet contains: " + set);

        // Check if the TreeSet contains an element
        System.out.println("TreeSet contains 'banana': " + set.contains("banana"));

        // Get the size of the TreeSet
        System.out.println("Size of TreeSet: " + set.size());

        // Clear the TreeSet
        set.clear();

        // Print the contents of the TreeSet after clearing
        System.out.println("TreeSet contains: " + set);
    }
}

Output

TreeSet contains: [apple, banana, orange, pear]
TreeSet contains: [apple, banana, orange, pear]
TreeSet contains: [apple, banana, pear]
TreeSet contains 'banana': true
Size of TreeSet: 3
TreeSet contains: []

Prime Course Trailer

Related Banners

Get PrepInsta Prime & get Access to all 200+ courses offered by PrepInsta in One Subscription

Get over 200+ course One Subscription

Courses like AI/ML, Cloud Computing, Ethical Hacking, C, C++, Java, Python, DSA (All Languages), Competitive Coding (All Languages), TCS, Infosys, Wipro, Amazon, DBMS, SQL and others

Checkout list of all the video courses in PrepInsta Prime Subscription

Checkout list of all the video courses in PrepInsta Prime Subscription