Set in Java

Java Set is a part of java.util package and extends java.util.Collection interface. It does not allow the use of duplicate elements and at max can accommodate only one null element. Few important features of Java Set interface are as follows:

  • The set interface is an unordered collection of objects in which duplicate values cannot be stored.
  • The Java Set does not provide control over the position of insertion or deletion of elements.
  • Basically, Set is implemented by HashSet, LinkedHashSet or TreeSet (sorted representation).
  • Set has various methods to add, remove clear, size, etc to enhance the usage of this interface

// Java code for adding elements in Set
import java.util.*;
public class Set_example
{
    public static void main(String[] args)
    {
        // Set demonstration using HashSet
        Set<String> hash_Set = new HashSet<String>();
        hash_Set.add("Geeks");
        hash_Set.add("For");
        hash_Set.add("Geeks");
        hash_Set.add("Example");
        hash_Set.add("Set");
        System.out.print("Set output without the duplicates");

        System.out.println(hash_Set);

        // Set demonstration using TreeSet
        System.out.print("Sorted Set after passing into TreeSet");
        Set<String> tree_Set = new TreeSet<String>(hash_Set);
        System.out.println(tree_Set);
    }
}
Output:

Set output without the duplicates[Set, Example, Geeks, For]
Sorted Set after passing into TreeSet[Example, For, Geeks, Set]

(Please note that we have entered a duplicate entity but it is not displayed in the output. Also, we can directly sort the entries by passing the unordered Set in as the parameter of TreeSet).

Note: As we can see the duplicate entry “Geeks” is ignored in the final output, Set interface doesn’t allow duplicate entries.
(Please note that we have entered a duplicate entity but it is not displayed in the output. Also, we can directly sort the entries by passing the unordered Set in as the parameter of TreeSet).



Now let’s look at some of the basic operations of the Set i.e. Union, Intersection and Difference.
Let’s take an example of two integer Sets:

  • [1, 3, 2, 4, 8, 9, 0]
  • [1, 3, 7, 5, 4, 0, 7, 5]

Union of a Set:
This allows the user to add one step to another. Since the Set will itself not allow any duplicate entries, we need not take care of the common values.
Expected Output:

Union : [0, 1, 2, 3, 4, 5, 7, 8, 9]

Intersection of a Set:
This operation is used to retain the common values from both Sets.
Expected Output:

Intersection : [0, 1, 3, 4]

Difference of a Set:
This operation is used to remove all the values of one Set from the other.
Expected Output:

Difference : [2, 8, 9]

Below program illustrates the working of various basic operations of Set interface:

// Java code for demonstrating union, intersection and difference
// on Set
import java.util.*;
public class Set_example
{
    public static void main(String args[])
    {
        Set<Integer> a = new HashSet<Integer>();
        a.addAll(Arrays.asList(new Integer[] {1, 3, 2, 4, 8, 9, 0}));
        Set<Integer> b = new HashSet<Integer>();
        b.addAll(Arrays.asList(new Integer[] {1, 3, 7, 5, 4, 0, 7, 5}));

        // To find union
        Set<Integer> union = new HashSet<Integer>(a);
        union.addAll(b);
        System.out.print("Union of the two Set");
        System.out.println(union);

        // To find intersection
        Set<Integer> intersection = new HashSet<Integer>(a);
        intersection.retainAll(b);
        System.out.print("Intersection of the two Set");
        System.out.println(intersection);

        // To find the symmetric difference
        Set<Integer> difference = new HashSet<Integer>(a);
        difference.removeAll(b);
        System.out.print("Difference of the two Set");
        System.out.println(difference);
    }
}
Output:

Union of the two Set[0, 1, 2, 3, 4, 5, 7, 8, 9]
Intersection of the two Set[0, 1, 3, 4]
Difference of the two Set[2, 8, 9]

Methods in Set Interface:

  1. add(): This method is used to add one object to the collection at a time.
  2. clear(): This method is used to remove all elements from the collection.
  3. contains(): This method is used to verify whether a specified element is present in the collection or not.
  4. isEmpty(): This method is used to check whether the collection is empty or not.
  5. iterator(): This is used to return an Iterator object, which may be used to retrieve an object from the collection.
  6. remove(): This is used to removes a specified object from the collection.
  7. size(): This is used to know the size or the number of elements present in the collection.

Below program illustrates the operations of few methods of Set Interface:

// Java code to illustrate clear()
import java.io.*;
import java.util.HashSet;

public class HashSetDemo{
    public static void main(String args[])
    {
        // Creating an empty HashSet
        HashSet<String> set = new HashSet<String>();

        // Use add() method to add elements into the Set
        set.add("Welcome");
        set.add("To");
        set.add("Geeks");
        set.add("4");
        set.add("Geeks");

        // Displaying the HashSet
        System.out.println("HashSet: " + set);
        
        // Using isEmpty() to verify for the emptiness
        System.out.println("The set is empty? "+
                                       set.isEmpty());
        
        // Does the set contain "Geeks"
        System.out.println("Does the set contain 'Geeks'?" 
                                 + set.contains("Geeks"));
                                 
        // Getting the size of the set
        System.out.println("The size of the set is "+
                                             set.size());
       
        // Removing "To" from the set
        set.remove("To");

        // Displaying the HashSet
        System.out.println("HashSet: " + set);        

        // Clearing the HashSet using clear() method
        set.clear();

        // Displaying the final Set after clearing;
        System.out.println("The final set: " + set);
    }
}
Output:

HashSet: [4, Geeks, Welcome, To]
The set is empty? false
Does the set contain 'Geeks'?true
The size of the set is 4
HashSet: [4, Geeks, Welcome]
The final set: []

This article is contributed by Pranjal Mathur. If you like GeeksforGeeks and would like to contribute, you can also write an article and mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.

Please write comments if you find anything incorrect, or you want to share more information about the topic discussed above



My Personal Notes arrow_drop_up

Improved By : ShreyasWaghmare




Practice Tags :
Article Tags :
Please write to us at contribute@geeksforgeeks.org to report any issue with the above content.

Recommended Posts:



1.8 Average Difficulty : 1.8/5.0
Based on 17 vote(s)






User Actions