Sets In Java

Photo by Luca Bravo on Unsplash

Sets In Java

Java (Sets)

·

11 min read

PREREQUISITES

MATHEMATICAL BACKGROUND OF SETS

A set is a collection of similar type of objects, for example a collection of birds. It will be as [Crow, Sparrow, Pigeon, Eagle]. In short sets are a well-defined collection of objects. In Java also we will consider these sets and perform operations like inserting, deleting, sorting etc on the set elements.

WHAT IS THE SET INTERFACE IN JAVA?

It is an extension to the collection interface. The set interface comes under the java.util package. Basically it is a collection of objects which doesn’t follow any particular order and has no duplicated values. As we discussed earlier this interface applies the mathematical sets. So what is the new element in these sets of java as compared to the mathematical sets? The answer is that this interface adds a new feature which will prohibit the insertion of the duplicate elements to our set. The methods in this interface are inherited from the collection interface.

Extension of the Set Interface

  • Sorted set
  • Navigable set extends the Sorted set
  • Tree set is a further extension

Example 1:

import java.util.*;
public class SetExample {
    public static void main(String[] args)
    {
        // Set demonstration using HashSet
        Set<String> set_java = new HashSet<String>();

        set_java.add("Great learning");
        set_java.add("in");
        set_java.add("Sets");
        set_java.add("in");
        set_java.add("Java");
        System.out.println(set_java);
    }
}

Output - [Java, Great learning, in, Sets]

DECLARATION OF SETS

In set Interface we always create an object. The objects are created with a class which can be HashSet or LinkedHashedSet or TreeSet etc. Syntax of declaration is as follows –

Set set = new LinkedHashSet ();

Note - The Obj is the type of object to be stored like Integer or String etc.

OPERATIONS ON SET INTERFACE

This interface can be utilized to do all the basic mathematical expressions that we perform with sets such as the intersection, union and difference.

Lets take two sets into consideration - Set A = [2, 23, 45, 56, 67, 78, 98]

Set B = [2, 34, 45, 59, 65, 78, 94]

  • Intersection – Intersection will return those elements common in both the sets. In our example, the intersection will be [2, 45, 78].
  • Union – Union is just like addition it will return the values present in both the sets. From our example union is [2, 23, 34, 45, 56, 59, 65, 67, 78, 94, 98].
  • Difference - Difference will remove all the common values from one set which are present in another set. From our example the difference set of Set A and Set B will be [ 23, 56, 67, 98].

Let have a look on an example program that does all these operations –

Example 2:

import java.util.*;    
public class SetOperations   
{    
    public static void main(String args[])    
    {    
        Integer[] A = {2, 23, 45, 56, 67, 78, 98};  
        Integer[] B = {2, 34, 45, 59, 65, 78, 94};  
        Set<Integer> setA = new HashSet<Integer>();    
        setA.addAll(Arrays.asList(A));    
        Set<Integer> setB = new HashSet<Integer>();    
        setB.addAll(Arrays.asList(B));    

        // Finding Union of setA and setB   
        Set<Integer> union_data = new HashSet<Integer>(setA);    
        union_data.addAll(setB);    
        System.out.print("Union of setA and setB is:");    
        System.out.println(union_data);    

        // Finding Intersection of setA and setB    
        Set<Integer> intersection_data = new HashSet<Integer>(setA);    
        intersection_data.retainAll(setB);    
        System.out.print("Intersection of setA and setB is:");    
        System.out.println(intersection_data);    

        // Finding Difference of setA and setB    
        Set<Integer> difference_data = new HashSet<Integer>(setA);    
        difference_data.removeAll(setB);    
        System.out.print("Difference of setA and setB is:");    
        System.out.println(difference_data);    
    }    
}

Output –

Union of setA and setB is:[65, 2, 98, 34, 67, 23, 56, 59, 45, 78, 94]

Intersection of setA and setB is:[2, 45, 78]

Difference of setA and setB is:[98, 67, 23, 56]

Explanation – In the above code there are three methods used :

  • addAll() – It performs the union operation and combines the elements.
  • retainAll() – It performs the intersection operation.
  • removeAll() – It performs the difference operation.

CLASSES USED IN SET INTERFACE OF JAVA

There are certain classes which we declare while making these sets. They are as follows –

  1. HashSet – This class is carried out under the Collection Framework and is an implementation of the hash table data structure. The data items in HashSet don’t follow a particular order and are inserted based on their Hash Code. Note – You can insert NULL elements in this class. Let’s see how to use this class through an example code –

    import java.util.*;
    class GLearning {
    public static void main(String[] args)
    {
      Set<String> gl = new HashSet<String>();
      // Adding elements into the HashSet
      gl.add("Java");
      gl.add("Ruby");
      gl.add("Python");
    
      // Adding the duplicate element Java
      gl.add("Java");
      // Displaying the HashSet
      System.out.println(gl);
    
      // Removing Ruby from HashSet
      gl.remove("Ruby");
      System.out.println("Set after removing "
                      + "Ruby:" + gl);
    
      // Iterating over hash set items
      System.out.println("Iterating over set:");
      Iterator<String> i = gl.iterator();
      while (i.hasNext())
          System.out.println(i.next());
    }
    }
    

Output –

[Java, Ruby, Python]

Set after removing Ruby:[Java, Python]

Iterating over set:

Java

Python

2. EnumSet – This class is also carried out under the Collection Framework. This is used with the enum data type in Java. This set is of special type as its implementation is faster than HashSet and performance is high. The elements of the EnumSet must be declared in the enum data type during creation of the set. It can be declared either implicitly or explicitly

Let’s see how to use this class through an example code –

import java.util.*;
enum Gl { Java, Python, Ruby, Swift, Kotlin }.
;
public class Glearning {
    public static void main(String[] args)
    {
        // Creating the set
        Set<Gl> setA;

        // Adding the elements in the set
        setA = EnumSet.of(Gl.Java, Gl.Ruby,
                        Gl.Swift, Gl.Python);
        System.out.println("Set A: " + setA);
    }
}

Output –

Set A: [Java, Python, Ruby, Swift]

3. LinkedHashSet – This class is also carried out under the Collection Framework. This class is used when we need to maintain the iteration in an orderly format. When we iterate through a HashSet there is no particular order followed. But in case of LinkedHashSet it iterates through the elements in an orderly manner that is as per they were inserted in the set. Let’s see how to use this class through an example code –

import java.util.*;
class Glearning {

    public static void main(String[] args)
    {
        Set<String> gl = new LinkedHashSet<String>();

        // Adding elements into the LinkedHashSet
        gl.add("Java");
        gl.add("Python");
        gl.add("Ruby");

        // Adding the duplicate element
        gl.add("Ruby");

        // Displaying the LinkedHashSet
        System.out.println(gl);

        // Removing items from LinkedHashSet
        gl.remove("Python");
        System.out.println("Set after removing "
                        + "Python:" + gl);

        // Iterating over linked hash set items
        System.out.println("Iterating over set:");
        Iterator<String> i = gl.iterator();
        while (i.hasNext())
            System.out.println(i.next());
    }
}

Output –

[Java, Python, Ruby]

Set after removing Python:[Java, Ruby]

Iterating over set:

Java

Ruby

4. TreeSet – It is a part of the collection framework. This class is implemented from the SortedSet Interface and as discussed earlier the Sorted Set extends the Set Interface. It is same as other sets the only difference is that it stores the elements in a sorted format. This class uses the Tree Data Structure for storage of the elements. By default is stores the elements in ascending order. To store them in descending order we use TreeSet.descendingIterator()

Let’s see how to use this class through an example code –

//Code to implement the tree set 
import java.util.*;
class Glearning {
    public static void main(String[] args)
    {
        Set<Integer> ts = new TreeSet<Integer>();

        // Adding elements into the TreeSet using add() method
        ts.add(3);
        ts.add(2);
        ts.add(1);

        // Adding the duplicate element
        ts.add(2);

        // Displaying the TreeSet
        System.out.println(ts);

        // Removing items from TreeSet using remove() method
        ts.remove(1);
        System.out.println("Set after removing "
                        + "1:" + ts);

        // Iterating over Tree set items
        System.out.println("Iterating over set:");
        Iterator<Integer> i = ts.iterator();
        while (i.hasNext())
            System.out.println(i.next());
    }
}

Output –

[1, 2, 3]

Set after removing 1:[2, 3]

Iterating over set:

2

3

METHODS IN SETS

1. add() - This method is used to add new values to the set. Note that the duplicate elements are restricted. Example –

import java.util.*;
class GLearning {
    public static void main(String[] args)
    {
        Set<String> gl = new HashSet<String>();

        // Elements are added using add()
        gl.add("GL");
        gl.add("GL");
        gl.add("B");
        gl.add("A");
        System.out.println(gl);
    }
}

Output –

[A, B, GL]

2. addAll() – This method will include or add all the members of one data set into another data set. Example –

import java.io.*;   
import java.util.*;  
class addAllJava {   
    public static void main(String args[])   
    {   
        Set<Integer> setA = new LinkedHashSet<Integer>();   
        setA.add(3);   
        setA.add(2);   
        setA.add(4);   
        System.out.println("Set: " + setA);  
        ArrayList<Integer> newsetB = new ArrayList<Integer>();   
        newsetB.add(5);   
        newsetB.add(6);   
        newsetB.add(7);  
        setA.addAll(newsetB);   
        System.out.println("Set: " + setA);       
    }   
}

Output –

Set: [3, 2, 4]

Set: [3, 2, 4, 5, 6, 7]

3. contains() – It shows whether one element is present in the set or not. It returns a Boolean value true or false. Example –

import java.io.*;   
import java.util.*;   
class containsMethod {   
    public static void main(String args[])   
    {   
        Set<Integer> pack = new LinkedHashSet<Integer>();   
        pack.add(10);   
        pack.add(20);   
        pack.add(30);   
        pack.add(40);   
        System.out.println("Set: " + pack);  
        System.out.println("Does the Set contain '90'? " + pack.contains(90));   
        System.out.println("Does the Set contain 'learning'? " + pack.contains("4"));  
        System.out.println("Does the Set contain '40'? " + pack.contains(40));  
    }   
}

Output –

Set: [10, 20, 30, 40]

Does the Set contain '90'? false

Does the Set contain 'learning'? false

Does the Set contain '40'? true

4. containsAll() –This methods checks whether the original set has elements of the new set too. Example –

import java.util.*;   
class containsAllMethod {   
    public static void main(String args[])   
    {   
        Set<Integer> setA = new LinkedHashSet<Integer>();   
        setA.add(10);   
        setA.add(20);   
        setA.add(30);   

        System.out.println("Set A: " + setA);  

        Set<Integer> setB = new LinkedHashSet<Integer>();   
        setB.add(10);   
        setB.add(20);   
        setB.add(30);   

       System.out.println("\nDoes Set A contains Set B?  : "+ setA.containsAll(setB));  

    }   
}

Output –

Set A: [10, 20, 30]

Does Set A contains Set B? : true

5. remove() – The particular values which the user wants to remove from that set can be removed using this method, Example –

import java.util.*;
class removeMethod {

    public static void main(String[] args)
    {
        Set<String> gl = new HashSet<String>();

        gl.add("X");
        gl.add("Y");
        gl.add("Z");
        gl.add("W");

        System.out.println("Before removing element " + gl);

        // Removing the element Y from the set gl
        gl.remove("Y");

        System.out.println("After removing element " + gl);
    }
}

Output –

Before removing element [W, X, Y, Z]

After removing element [W, X, Z]

6. clear() – This method is used to entirely empty the set or remove all the values from the set, The set then becomes null. Example –

import java.io.*;   
import java.util.*;   
public class clearMethod {   
    public static void main(String args[])   
    {   
        Set<Integer> setA = new LinkedHashSet<Integer>();   

        setA.add(10);   
        setA.add(20);   
        setA.add(30);   
        System.out.println("Set: " + setA);  

        setA.clear();   
        System.out.println("The final set: " + setA);   
    }   
}

Output –

Set: [10, 20, 30]

The final set: []

7. removeAll() – This method is used to remove all the selected elements from the set.

Example –

import java.io.*;   
import java.util.*;  
class removeAllMethod {   
    public static void main(String args[])   
    {   
        Set<Integer> setA = new LinkedHashSet<Integer>();   
        setA.add(30);   
        setA.add(20);   
        setA.add(40);  
        setA.add(90);   
        setA.add(70);   
        System.out.println("Set A: " + setA);  

        ArrayList<Integer> setB = new ArrayList<Integer>();   
        setB.add(90);   
        setB.add(70);   
        setB.add(80);  
        System.out.println("Set B: " + setB);  

        setA.removeAll(setB);  
        System.out.println("Set A after removing Set B elements is given as: " + setA);         
    }   
}

Output –

Set A: [30, 20, 40, 90, 70]

Set B: [90, 70, 80]

Set A after removing Set B elements is given as: [30, 20, 40]

8. isEmpty() – This method returns a Boolean value whether the set is entirely empty or not. Example –

import java.io.*;   
import java.util.*;   
class isEmptyMethod {   
    public static void main(String args[])   
    {   
        Set<Integer> setA = new LinkedHashSet<Integer>();   
        setA.add(10);   
        setA.add(20);   
        setA.add(30);   
        setA.add(40);   
        setA.add(50);   
        System.out.println("Set A: " + setA);  
       System.out.println("Is Set A empty?: "+ setA.isEmpty());      
    }   
}

Output –

Set A: [10, 20, 30, 40, 50]

Is Set A empty?: false

9. iterator() – This method lets us iterate through the set. It retrieves the elements of the set one by one. Example –

import java.util.*;   
class iteratorMethod {   
    public static void main(String args[])   
    {   
        Set<Integer> setA = new LinkedHashSet<Integer>();   
        setA.add(10);   
        setA.add(20);   
        setA .add(30);   
        setA.add(40);   
        setA.add(50);   
        setA.add(60);   
        System.out.println("Set A: " + setA);  

        Iterator setB = setA.iterator();  
        System.out.println("The set B values are: ");   
        while (setB.hasNext()) {   
            System.out.println(setB.next());   
        }  
    }   
}

Output –

Set A: [10, 20, 30, 40, 50, 60]

The set B values are:

10

20

30

40

50

60

10. retainAll() – This method is just the opposite of the removeAll() method. It will retain or keep back the elements of the new set in the original set. Example –

import java.io.*;   
import java.util.*;  
class retainAllMethod {   
    public static void main(String args[])   
    {   
        Set<Integer> setA = new LinkedHashSet<Integer>();   
        setA.add(10);   
        setA.add(20);   
        setA.add(30);  
        setA.add(40);   
        setA.add(50);   
        System.out.println("Set A: " + setA);  

        ArrayList<Integer> setB = new ArrayList<Integer>();   
        setB.add(40);   
        setB.add(50);   
        System.out.println("Set B: " + setB);  

        setA.retainAll(setB);      
        System.out.println("Set A after retaining Set B elements is given as: " + setA);        
    }   
}

Output –

Set A: [10, 20, 30, 40, 50]

Set B: [40, 50]

Set A after retaining Set B elements is given as: [40, 50]

11. size() – Whenever we need to extract the size of the set we use this method. It returns the number of data items/elements present in the set. Example –

import java.io.*;   
import java.util.*;  
class sizeMethod {   
    public static void main(String args[])   
    {   
        Set<Integer> setA = new LinkedHashSet<Integer>();   
        setA.add(10);   
        setA.add(20);   
        setA.add(30);  
        setA.add(40);   
        setA.add(50);   
        System.out.println("Set A: " + setA);  

        System.out.println("Size of the Set A is given as: " + setA.size());       
    }   
}

Output –

Set A: [10, 20, 30, 40, 50]

Size of the Set A is given as: 5

12. hashCode() – This method is used to gain the hash code value of that particular set. It will the return the value in integer format.

Example –

import java.io.*;   
import java.util.*;   
class hashCodeMethod {   
    public static void main(String args[])   
    {   
        Set<Integer> setA = new LinkedHashSet<Integer>();   
        setA.add(10);   
        setA.add(20);   
        setA.add(30);   
        setA.add(40);   
        setA.add(50);   
        setA.add(60);   
        System.out.println("Set A: " + setA);  
        System.out.println("The hash code value of Set A is: "+ setA.hashCode());      
    }   
}

Output –

Set A: [10, 20, 30, 40, 50, 60]

The hash code value of Set A is: 210

13. toArray() – It converts the sets elements into array elements. That means it makes an array of the set elements.

Conclusion

The set interface in Java lets us perform various functions and tasks in our program. It lets us insert, delete, retain, and sort the elements of our data set. Overall, this interface increases the efficiency of our code and makes it easy to build different features using the data structures of this interface.