Set Interface in Java

Set Interface in Java: The Java Collections Framework is fundamental and essential, 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 will learn one more interface of the collection framework: the Set interface.

The topics that are going to be discussed in this post are:

  • 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.

Hierarchy of Set Interface
Hierarchy of Set Interface

Set interface in Java

The set interface extends the collection interface. When there is a requirement to store a group of individual objects as a single entity where duplicates are not allowed and insertion order is not preserved, we should go for the List.

Like in List, the Set interface does not have a particular order and does not provide control over the position of the elements.

Set Interface in Java Explanation
Set Interface in Java Explanation

How to create a Set?

We can define a new Set interface like the one below.

Set<E> num = new HashSet<>();

We try to define the set generically, but if you want to specify with some specific type, you can mention it below.

Set<Integer> num = new HashSet<>();

Different Methods Of Set Interface In Java

Like the List interface, the Set interface also has many methods; we try to share all those methods with a simple explanation in a tabular format below

MethodDescription
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 accessing the elements.

  • HashSet does not maintain any order of the insertion of the elements, so when we try to retrieve the elements, 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; you can read that, too.
  • LinkedHashSet is also implementing the set interface. Still, when we try retrieving the elements by iterating them, we get them in the same order in which they were 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 maintains the insertion order; values are retrieved in the same order in which they are added. It uses a doubly linked list to obtain this functionality. You can check our detailed post about the TreeSet class in Java to learn more.

Different Operation On List Interface

We will know about essential operations like adding and removing, checking whether the set is empty or not, the size of the set, iterating the elements, and searching for an element. And some other essential operations like union, Insertion, and Difference.

Add & Remove Operation In Set Interface:

Using the add() method, we can add the elements into a Set. Similarly, with the help of the Remove() method, we can also remove a specific element from the set. You can check the below program for a 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 whether the Set is empty or not. If the Set is empty, it returns true and 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 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 find out whether the specific elements are present in the set. If the element is present in the set, you will get true; if the element is not, 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 that are acting on a single set, but the set provides us with some other methods that can act on multiple methods; those are :

  • Union: We can use this operation to add one set with another.
  • Intersection: We can get the common elements between the two sets using this operation.
  • 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.
  • The set interface has 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.

I love open-source technologies and am very passionate about software development. I like to share my knowledge with others, especially on technology that's why I have given all the examples as simple as possible to understand for beginners. All the code posted on my blog is developed, compiled, and tested in my development environment. If you find any mistakes or bugs, Please drop an email to softwaretestingo.com@gmail.com, or You can join me on Linkedin.

Leave a Comment