Set in Java

Last Updated : 14 Oct 2026

In Java, the Set is an interface that belongs to java.util package. It extends the Collection interface. The Set interface is used to create the mathematical set. It uses the Collection interface's methods to avoid the insertion of the same elements. SortedSet and NavigableSet are two interfaces that extend the Set implementation.

Set in Java

In the above diagram, the NavigableSet and SortedSet are both the interfaces. The NavigableSet extends the SortedSet, so it will not retain the insertion order and store the data in a sorted way.

The Set interface implemented by several classes, including HashSet, TreeSet, and LinkedHashSet. Sets are widely used for tasks where uniqueness of elements is a priority, such as storing unique identifiers, filtering duplicate entries from data, or implementing mathematical set operations.

Features of Set

  • No Duplicates: We cannot add the same item twice.
  • Null Values: It accepts at most one null value, except for TreeSet.
  • No Indexes: We cannot access items by position numbers like we do in a List.
  • Fast Searches: It is optimized for checking if an item exists.

Set Methods

There are several methods available in the Set interface that can be used to perform a certain operation on sets.

MethodDescription
add(E e)It adds the specified element to this set if it is not already present (optional operation).
addAll(Collection<? extends E> c)It adds all of the elements in the specified collection to this set if they are not already present (optional operation).
clear()It removes all of the elements from this set (optional operation).
contains(Object o)It returns true if this set contains the specified element.
containsAll(Collection<?> c)It returns true if this set contains all of the elements of the specified collection.
equals(Object o)It compares the specified object with this set for equality.
hashCode()It returns the hash code value for this set.
isEmpty()It returns true if this set contains no elements.
iterator()It returns an iterator over the elements in this set.
remove(Object o)It removes the specified element from this set if it is present (optional operation).
removeAll(Collection<?> c)It removes from this set all of its elements that are contained in the specified collection (optional operation).
retainAll(Collection<?> c)It retains only the elements in this set that are contained in the specified collection (optional operation).
size()It returns the number of elements in this set (its cardinality).
spliterator()It creates a Spliterator over the elements in this set.
toArray()It returns an array containing all of the elements in this set.
toArray(T[] a)It returns an array containing all of the elements in this set; the runtime type of the returned array is that of the specified array.

Set Operations

On the Set, we can perform all the basic mathematical operations like intersection, union and difference.

Suppose, we have two sets, i.e., set1 = [22, 45, 33, 66, 55, 34, 77] and set2 = [33, 2, 83, 45, 3, 12, 55]. We can perform the following operation on the Set:

  • Intersection:The intersection operation returns all those elements which are present in both the set. The intersection of set1 and set2 will be [33, 45, 55].
  • Union:The union operation returns all the elements of set1 and set2 in a single set, and that set can either be set1 or set2. The union of set1 and set2 will be [2, 3, 12, 22, 33, 34, 45, 55, 66, 77, 83].
  • Difference:The difference operation deletes the values from the set which are present in another set. The difference of the set1 and set2 will be [66, 34, 22, 77].

In set, the addAll() method is used to perform the union, the retainAll() method is used to perform the intersection and the removeAll() method is used to find difference between two sets.

Example: Performing Intersection, Union, and Difference Operations

Java

import java.util.*;      
public class Main  
{      
    public static void main(String args[])      
    {      
        Integer[] A = {22, 45,33, 66, 55, 34, 77};    
        Integer[] B = {33, 2, 83, 45, 3, 12, 55};    
        Set<Integer> set1 = new HashSet<Integer>();      
        set1.addAll(Arrays.asList(A));      
        Set<Integer> set2 = new HashSet<Integer>();      
        set2.addAll(Arrays.asList(B));      
        // Finding Union of set1 and set2     
        Set<Integer> union_data = new HashSet<Integer>(set1);      
        union_data.addAll(set2);      
        System.out.print("Union of set1 and set2 is: ");      
        System.out.println(union_data);      
        // Finding Intersection of set1 and set2      
        Set<Integer> intersection_data = new HashSet<Integer>(set1);      
        intersection_data.retainAll(set2);      
        System.out.print("Intersection of set1 and set2 is: ");      
        System.out.println(intersection_data);      
        // Finding Difference of set1 and set2      
        Set<Integer> difference_data = new HashSet<Integer>(set1);      
        difference_data.removeAll(set2);      
        System.out.print("Difference of set1 and set2 is: ");      
        System.out.println(difference_data);      
    }      
}
Compile and Run

Output:

Union of set1 and set2 is: [33, 66, 34, 2, 83, 3, 22, 55, 12, 45, 77]
Intersection of set1 and set2 is: [33, 55, 45]
Difference of set1 and set2 is: [66, 34, 22, 77]

Explanation

In the above program, first, we have created two arrays, i.e., A and B of type integer. After that, we have created two set, i.e., set1 and set2 of type integer. We have converted both the array into a list and add the elements of array A into set1 and elements of array B into set2.

For performing the union operation, we have created a new set union_data with the same element of the set1. After that we call the addAll() method of set and pass the set2 as an argument to it. This method adds all those elements to the union_data which are not present in it and gives the union of both sets.

For performing the intersection operation, we have created a new set intersection_data with the same element of the set1. After that we call the retainAll() method of set and pass the set2 as an argument to it. This method gets all those elements from the intersection_data which are present in set2 and store it in the intersection_data. Now, the intersection_data contains the intersect value of both the sets.

For finding the difference of two sets, we have created a new set difference_data with the same element of the set1. After that we call the removeAll() method of set and pass the set2 as an argument to it. This method removes all those elements from the difference_data which are present in the set2 and gives the difference of both the sets.

1) Set.add() Method

The add() method insert a new value to the set. The method returns true and false depending on the presence of the insertion element. It returns false if the element is already present in the set and returns true if it is not present in the set.

Syntax:

boolean add(type element).

Example

import java.io.*;     
import java.util.*;     
public class Main {     
    public static void main(String args[])     
    {     
        Set<Integer> data = new LinkedHashSet<Integer>();     
        data.add(31);     
        data.add(21);     
        data.add(41);     
        data.add(11);     
        data.add(61);     
        data.add(51);     
        System.out.println("data: " + data);     
    }     
}    
Compile and Run

Output:

data: [31, 21, 41, 11, 61, 51]

2) Set.addAll() Method

The addAll() method appends all the elements of the specified collection to the set.

Syntax:

boolean addAll(Collection data)

Example

import java.io.*;     
import java.util.*;    
public class Main {     
    public static void main(String args[])     
    {     
        Set<Integer> data = new LinkedHashSet<Integer>();     
        data.add(31);     
        data.add(21);     
        data.add(41);     
        System.out.println("Set: " + data);    
        ArrayList<Integer> newData = new ArrayList<Integer>();     
        newData.add(91);     
        newData.add(71);     
        newData.add(81);    
        data.addAll(newData);     
        System.out.println("Set: " + data);         
    }     
}    
Compile and Run

Output:

Set: [31, 21, 41]
Set: [31, 21, 41, 91, 71, 81]

3) Set.clear() Method

The method removes all the elements from the set. It does not delete the reference of the set. It deletes only the elements of the set.

Syntax:

void clear()

Example

import java.io.*;   
import java.util.*;   
public class Main {   
    public static void main(String args[])   
    {   
        Set<Integer> data = new LinkedHashSet<Integer>();   
        data.add(31);   
        data.add(21);   
        data.add(41);   
        System.out.println("Set: " + data);  
        data.clear();   
        System.out.println("The final set: " + data);   
    }   
}  
Compile and Run

Output:

Set: [31, 21, 41]
The final set: []

4) Set.contains() Method

The contains() method is used to know the presence of an element in the set. Its return value is true or false depending on the presence of the element.

Syntax:

boolean contains(Object element)

Example

import java.io.*;   
import java.util.*;   
public class Main {   
    public static void main(String args[])   
    {   
        Set<Integer> data = new LinkedHashSet<Integer>();   
        data.add(31);   
        data.add(21);   
        data.add(41);   
        data.add(51);   
        data.add(11);   
        data.add(81);   
        System.out.println("Set: " + data);  
        System.out.println("Does the Set contain '91'?" + data.contains(91));   
        System.out.println("Does the Set contain 'tpointtech'? " + data.contains("4"));  
        System.out.println("Does the Set contain '51'? " + data.contains(51));  
    }   
}  
Compile and Run

Output:

Set: [31, 21, 41, 51, 11, 81]
Does the Set contain '91'? false
Does the Set contain 'tpointtech'? false
Does the Set contain '51'? true

5) Set.containsAll() Method

The method is used to check whether all the elements of the collection are available in the existing set or not. It returns true if all the elements of the collection are present in the set and returns false even if one of the elements is missing in the existing set.

Syntax:

public boolean containsAll(Collection data)

Example

import java.io.*;   
import java.util.*;   
public class Main {   
    public static void main(String args[])   
    {   
        Set<Integer> data = new LinkedHashSet<Integer>();   
        data.add(31);   
        data.add(21);   
        data.add(41);   
        data.add(51);   
        data.add(11);   
        data.add(81);   
        System.out.println("data: " + data);  
        Set<Integer> newData = new LinkedHashSet<Integer>();   
        newData.add(31);   
        newData.add(21);   
        newData.add(41);   
  System.out.println("\nDoes data contain newData?: "+ data.containsAll(newData));  
    }   
}  
Compile and Run

Output:

data: [31, 21, 41, 51, 11, 81]
Does data contain newData?: true

6) Set.hashCode() Method

The method is used to derive the hash code value for the current instance of the set. It returns hash code value of integer type.

Syntax:

public int hashCode()

Example

import java.io.*;   
import java.util.*;   
public class Main {   
    public static void main(String args[])   
    {   
        Set<Integer> data = new LinkedHashSet<Integer>();   
        data.add(31);   
        data.add(21);   
        data.add(41);   
        data.add(51);   
        data.add(11);   
        data.add(81);   
        System.out.println("data: " + data);  
        System.out.println("\nThe hash code value of set is: "+ data.hashCode());      
    }   
}  
Compile and Run

Output:

data: [31, 21, 41, 51, 11, 81]
The hash code value of set is: 236

7) Set.isEmpty() Method

The isEmpty() method checks whether the set is empty or not. It returns true if the set is empty, else returns false.

Syntax:

boolean isEmpty()

Example

import java.io.*;   
import java.util.*;   
public class Main {   
    public static void main(String args[])   
    {   
        Set<Integer> data = new LinkedHashSet<Integer>();   
        data.add(31);   
        data.add(21);   
        data.add(41);   
        data.add(51);   
        data.add(11);   
        data.add(81);   
        System.out.println("data: " + data);  
       System.out.println("\nIs data empty? "+ data.isEmpty());      
    }   
}  
Compile and Run

Output:

data: [31, 21, 41, 51, 11, 81]
Is data empty? false

8) Set.iterator() Method

The iterator() method is used to find the iterator of the set. The iterator is used to get the element one by one.

Syntax:

Iterator iterate_value = set1.iterator();

Example

import java.io.*;   
import java.util.*;   
public class Main {   
    public static void main(String args[])   
    {   
        Set<Integer> data = new LinkedHashSet<Integer>();   
        data.add(31);   
        data.add(21);   
        data.add(41);   
        data.add(51);   
        data.add(11);   
        data.add(81);   
        System.out.println("data: " + data);  
        Iterator newData = data.iterator();  
        System.out.println("The NewData values are: ");   
        while (newData.hasNext()) {   
            System.out.println(newData.next());   
        }  
    }   
}  
Compile and Run

Output:

data: [31, 21, 41, 51, 11, 81]
The NewData values are: 
31
21
41
51
11
81

9) Set.remove() Method

The method is used to remove a specified element from the Set. Its return value depends on the availability of the element. It returns true if the element is available in the set and returns false if it is unavailable in the set.

Syntax:

boolean remove(Object O)

Example

import java.io.*;   
import java.util.*;   
public class Main {   
    public static void main(String args[])   
    {   
        Set<Integer> data = new LinkedHashSet<Integer>();   
        data.add(31);   
        data.add(21);   
        data.add(41);   
        data.add(51);   
        data.add(11);   
        data.add(81);   
        System.out.println("data: " + data);  
        data.remove(81);  
        data.remove(21);  
        data.remove(11);      
        System.out.println("data after removing elements: " + data);  
    }   
}  
Compile and Run

Output:

data: [31, 21, 41, 51, 11, 81]
data after removing elements: [31, 41, 51]

11) Set.removeAll() Method

The method removes all the elements of the existing set from the specified collection.

Syntax:

public boolean removeAll(Collection data)

Example

import java.io.*;   
import java.util.*;  
public class Main {   
    public static void main(String args[])   
    {   
        Set<Integer> data = new LinkedHashSet<Integer>();   
        data.add(31);   
        data.add(21);   
        data.add(41);  
        data.add(91);   
        data.add(71);   
        data.add(81);         
        System.out.println("data: " + data);  
        ArrayList<Integer> newData = new ArrayList<Integer>();   
        newData.add(91);   
        newData.add(71);   
        newData.add(81);  
        System.out.println("NewData: " + newData);  
        data.removeAll(newData);  
        System.out.println("data after removing Newdata elements: " + data);         
    }   
}  
Compile and Run

Output:

data: [31, 21, 41, 91, 71, 81]
NewData: [91, 71, 81]
data after removing Newdata elements: [31, 21, 41]

11) Set.retainAll() Method

The method retains all the elements from the set specified in the given collection.

Syntax:

public boolean retainAll(Collection data)

Example

import java.io.*;   
import java.util.*;  
public class Main {   
    public static void main(String args[])   
    {   
        Set<Integer> data = new LinkedHashSet<Integer>();   
        data.add(31);   
        data.add(21);   
        data.add(41);  
        data.add(91);   
        data.add(71);   
        data.add(81);         
        System.out.println("data: " + data);  
        ArrayList<Integer> newData = new ArrayList<Integer>();   
        newData.add(91);   
        newData.add(71);   
        newData.add(81);  
        System.out.println("newData: " + newData);  
        data.retainAll(newData);      
        System.out.println("data after retaining newdata elements: " + data);        
    }   
}  
Compile and Run

Output:

data: [31, 21, 41, 91, 71, 81]
newData: [91, 71, 81]
data after retaining newdata elements: [91, 71, 81]

12) Set.size() Method

The method returns the size of the set.

Syntax:

int size()

Example

import java.io.*;   
import java.util.*;  
public class Main {   
    public static void main(String args[])   
    {   
        Set<Integer> data = new LinkedHashSet<Integer>();   
        data.add(31);   
        data.add(21);   
        data.add(41);  
        data.add(91);   
        data.add(71);   
        data.add(81);         
        System.out.println("data: " + data);  
        System.out.println("size of the data is: " + data.size());       
    }   
}  
Compile and Run

Output:

data: [31, 21, 41, 91, 71, 81]
size of the data is: 6

13) Set.removeAll() Method

The method is used to create an array with the same elements of the set.

Syntax:

Object[] toArray()

Example

import java.io.*;     
import java.util.*;    
public class Main {     
    public static void main(String args[])     
    {     
        Set<Integer> data = new LinkedHashSet<Integer>();     
        data.add(31);     
        data.add(21);     
        data.add(41);    
        data.add(91);     
        data.add(71);     
        data.add(81);           
        System.out.println("data: " + data);    
        Object[] array_data = data.toArray();     
        System.out.println("The array is:");     
        for (int i = 0; i < array_data.length; i++)     
            System.out.println(array_data[i]);          
    }     
}    
Compile and Run

Output:

data: [31, 21, 41, 91, 71, 81]
The array is:
31
21
41
91
71
81

Common Set Implementations

  • HashSet: HashSet is one of the most commonly used Set implementations in Java. It uses a hash table for storage and provides constant-time performance for basic operations like add, remove, and contains. However, it does not guarantee the order of elements.
  • TreeSet: TreeSet is an implementation of the Set interface that uses a Red-Black tree for storage. It maintains elements in sorted order that makes it suitable for scenarios where elements need to be accessed in a sorted manner.
  • LinkedHashSet: LinkedHashSet is a hybrid data structure that combines a hash table with a linked list. It maintains a predictable iteration order that is the order in which elements were inserted into the set.