Set Interface in Java: The Java Collections Framework is a fundamental and essential framework, and without any understanding of those concepts, no one can do better programming. That’s why any strong Java developer should know like the back of their hand. In this post, we are going to learn one more interface of the collection framework, which is the Set interface.
The topics which are going to discuss on this post is:
- Hierarchy of Set Interface
- Set interface in Java
- How to create a Set?
- Different Method of List Interface
- Set Implementations
- Different Operation On List Interface
Hierarchy of Set Interface
The Set interface extends the collection interface, whereas the collection interface extends the iterable interface. You can see the diagram of the complete Hierarchy of Set Interface for better understanding.

Set interface in Java
The set interface extends the collection interface. When there is a requirement is to store a group of the individual object as a single entity where duplicates are not allowed and insertion order not preserved then we should go for the List.
Like in List, the Set interface does not have a particular order and also not provide control over the position of the elements.

How to create a Set?
We can define a new Set interface like below
Set<E> num = new HashSet<>();
We try to define the set generically, but if you want to specify with some specific type then you can mention like below
Set<Integer> num = new HashSet<>();
Different Methods Of Set Interface In Java
Like List interface, Set interface also so many methods, we try to share all those methods with the simple explanation in a tabular format below
Method | Description |
add( ) | Adds an object to the collection |
clear( ) | Removes all objects from the collection. |
contains( ) | Returns true if a specified object is an element within the collection. |
isEmpty( ) | Returns true if the collection has no elements. |
iterator( ) | Returns an Iterator object for the collection, which may be used to retrieve an object. |
remove( ) | Removes a specified object from the collection. |
size( ) | Returns the number of elements in the collection. |
Set Implementations
Different classes implement the Set interface in the collection framework. That is HashSet, LinkedHashSet, or the TreeSet.
Each of these implementations acts differently while iterating the set, mostly concerning the ordering of the elements, and the time taken for insertion and for accessing the elements.
- HashSet does not maintain any order of the insertion of the elements, so when we try to retrieve the elements, also we do not get those elements in the same order as we have entered. We have discussed more details in a separate post on HashSet In Java, and you can read that too.
- LinkedHashSet is also implementing the set interface. Still, when we are trying to retrieve the elements by iterating those, then we get the elements as in the same order in which they have added. We can get this because LinkedHashSet implements the doubly linked list data structure. For more about the LinkedHashSet tutorial, you can read our detailed post.
- TreeSet has also implemented the set interface, but it maintains the insertion order that is values are retrieved in the same order in which they are added. It uses a doubly linked list to obtain this functionality. To learn in detail, you can check our details post about TreeSet class in Java.
Different Operation On List Interface
We are going to know about the essential operation like add, remove, Check the set is empty or not, Size of the set, Iterating the elements, Searching an element. And some other essential operations like union, Insertion, and Difference.
Add & Remove Operation In Set Interface:
By using the add() method we can add the elements into a Set Similarly with the help of Remove() method we can remove a specific element from the set also. You can check the below program for better understanding:
package com.SoftwareTestingO.Java.basics; import java.util.HashSet; import java.util.Set; public class Demo{ public static void main(String args[]) { // Creating an Empty Set Set<String> set = new HashSet<String>(); //Adding elements to the set set.add("John"); set.add("Doe"); // Display the set System.out.println("Set: " + set); // Removing the element “Doe” using remove() method set.remove("Doe"); // Displaying the modified set System.out.println("Set : "+ set); } }
Output:
Set: [John, Doe] Set : [John]
Is Empty Method In Set Interface
This method helps us to check the Set is empty or not. If the Set in empty then it returns true and it returns false if the set has elements.
package com.SoftwareTestingO.Java.basics; import java.util.HashSet; import java.util.Set; public class Demo { public static void main(String args[]) { Set<String> javaSet = new HashSet<String>(); // Adding elements to the Set javaSet.add("John"); javaSet.add("Doe"); // Display the set System.out.println("Set: " + javaSet); // Checking whether the set is empty System.out.println("Empty Set : " + javaSet.isEmpty()); // Clearing the set using the clear() method javaSet.clear(); // Checking whether the set is empty System.out.println("Empty Set : " + javaSet.isEmpty()); } }
Output:
Set: [John, Doe] Empty Set : false Empty Set : true
Size Method
With the help of the size() method, you can get the size of the set which is the number of the elements present in the set.
package com.SoftwareTestingO.Java.basics; import java.util.HashSet; import java.util.Set; public class Demo { public static void main(String args[]) { // Creating a set Set<String> set = new HashSet<String>(); set.add("John"); set.add("Doe"); System.out.println("Set: " + set); // Displaying the size of the sent System.out.println("Size of the set : " + set.size()); } }
Output:
Set: [John, Doe] Size of the set : 2
Iterating Over A Set
We can iterate the set elements by using the iterator.
package com.SoftwareTestingO.Java.basics; import java.util.HashSet; import java.util.Iterator; public class Demo { public static <E> void main(String args[]) { // Creating a HashSet HashSet<String> javaSet = new HashSet<String>(); javaSet.add("John"); javaSet.add("Doe"); // Displaying the set System.out.println("HashSet: " + javaSet); // Creating an iterator Iterator<String> itr = javaSet.iterator(); // Displaying the values after iteration System.out.println("Iterator values: "); while (itr.hasNext()) { System.out.println(itr.next()); } } }
Output:
HashSet: [John, Doe] Iterator values: John Doe
Searching in A Set
By using the contains () method in the set we can able to find out that the specific elements are present in the set or not. If the element is present in the set then you will get true and if the element is not present then you will get false.
package com.SoftwareTestingO.Java.basics; import java.util.HashSet; public class Demo { public static void main(String args[]) { // Creating a HashSet HashSet<String> javaSet = new HashSet<String>(); javaSet.add("John"); javaSet.add("Doe"); // Displaying the HashSet System.out.println("HashSet: " + javaSet); // Checking for “John” in the set System.out.println("John in set: " + javaSet.contains("John")); // Checking for "Hazel" in set System.out.println("Hazel in set: " + javaSet.contains("Hazel")); } }
Output:
HashSet: [John, Doe] John in set: true Hazel in set: false
Basic Operation On Sets in Java
As of now, we have discussed those methods which are acting on a single set but the set provides us some other methods which can act on multiple methods those are :
- Union: We can use this operation to add one set with another.
- Intersection: Using this operation, we can able to get the common elements between the two sets.
- Difference: This operation removes the values of one set from the other set. (For example, the set difference of s1 minus s2 is the set containing all of the elements found in s1 but not in s2.)
If you are still confused then check the below program so that you will get a clear idea:
package com.SoftwareTestingO.Java.basics; import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Demo { public static void main(String args[]) { Set<Integer> d = new HashSet<Integer>(); d.addAll(Arrays.asList(new Integer[] {3, 2, 1, 9, 6, 4, 0})); Set<Integer> e = new HashSet<Integer>(); e.addAll(Arrays.asList(new Integer[] {3, 1, 9, 5, 2, 0, 7,})); // Union Operation Set<Integer> union = new HashSet<Integer>(d); union.addAll(e); System.out.println("Union :" + union); // Intersection Operation Set<Integer> intersection = new HashSet<Integer>(d); intersection.retainAll(e); System.out.println("Intersection :" + intersection); // Difference Operation Set<Integer> difference = new HashSet<Integer>(d); difference.removeAll(e); System.out.println("Difference :" + difference); } }
Output:
Union :[0, 1, 2, 3, 4, 5, 6, 7, 9] Intersection :[0, 1, 2, 3, 9] Difference :[4, 6]
Important Points to Remember Java Set
In this section, we will discuss some of the important points about Java Set:
- Java Set interface is a member of the Java Collections Framework.
- Unlike List, Set DOES NOT allow you to add duplicate elements.
- The set allows you to add at most one null element only.
- Set interface got one default method in Java 8: spliterator.
- Unlike List and arrays, Set does NOT support indexes or positions of its elements.
- Set supports Generics, and we should use it whenever possible. Using Generics with Set will avoid ClassCastException at runtime.
- We can use Set interface implementations to maintain unique elements.
Ref: article
Leave a Reply