Set in Java | Set Methods Example

In this tutorial, we will learn Set in Java with example programs. The set is an interface that was introduced in Java 1.2 version.

Java Set is a kind of an unordered collection of elements that are used to remove duplicate elements in the Java programming. It holds a single reference to an object.

The set interface does not provide two references to the same object, two references to null, or references to two objects a and b  such that a.equals(b).

Set interface does not provide any additional methods. It uses methods defined by collection but places additional restrictions on those methods.

When set uses add() or addAll() methods defined by the collection interface, it does not add an element to the set if the set already contains that element. That means an element can exist only once in the set. Let’s see in detail.

Set in Java


➲ A set in Java is a collection of elements or objects that are not stored in a particular order. It is used to store the collection of elements without duplicate. That is, set does not allow duplicate elements. It contains only unique elements.

➲ Set will not add an element to set if set already contains that element.
➲ Set in Java is an unordered collection. That means the order is not maintained while storing elements. While retrieving we may not get the same order as that we put elements.
➲ Java Set uses map based structure for its implementation. It can be iterated by using Iterator but cannot be iterated by using ListIterator.  

 

➲ Most of the set implementations allow adding only one null element. Tree set does not allow to add null element. 
➲ Set is not an indexed based structure in Java. Therefore, we cannot access elements by their index position. 
➲ It does not provide any get method like a list.

Hierarchy of Set Interface in Java


Java Set interface extends the java.util.collection interface. The java.util.SortedSet interface extends set interface to provide the sorted set of elements. Three classes such as HashSet, LinkedHashSet, and TreeSet implements set interface.

ConcurrentSkipListSet and EnumSet classes also implements set interface. The hierarchy diagram of the set interface is shown in below figure. 

Hierarchy of set in Java

Java Set Methods


A set interface has the following various useful methods such as add, remove, clear, size, etc to enhance the usage of a set interface in the collections framework. They are listed in the table:
  SN           Method                                                   Description
  1. boolean add(Object o) It is used to add the specified element in this set.
  2. boolean addAll(Collection c) This method adds all the elements in the given collection.
  3. int size() It is used to get the number of elements in the set.
  4. boolean isEmpty() This method checks that the set is empty or not.
  5. void clear() It is used to remove all the elements from the set.
  6. boolean contains(Object o) This method returns true if this set contains the given element.
  7. boolean containsAll(Collection c) This method returns true if this set contains all the elements of the given collection.
  8. boolean remove(Object o) It is used to remove the specified element from this set.
  9. boolean removeAll(Collection c) It removes all the elements in the given collection from the set.
 10. Iterator iterate() It returns an Iterator over the elements in this set.
 11. boolean equals(Object o) It is used to compare the given element for equility in this set.
 12. int hashCode() It is used to get the hashCode value for this set.

Ways to create a Generic Set object in Java


1. We can create a generic Set object by using the implementation of the HashSet, LInkedHashSet, TreeSet etc like this:


Syntax:
Set<T> set = new HashSet<T>(); where T is type of generic.
Set<T> set = new LinkedHashSet<T>();
Set<T> set = new TreeSet<T>();

For example:
   Set<Integer> set = new HashSet<Integer>();
   Set<String> set2 = new LinkedHashSet<String>();

Performing Basic Operations on Set with Example Programs


1. Adding Elements to Set: The add() method returns true if set does not contain the specified element. If set already contains the specified element then it will return false. Let’s take an example program based on it.
Program source code 1:
package setProgram; 
import java.util.HashSet; 
import java.util.LinkedHashSet; 
import java.util.Set; 
public class SetExample1 
{ 
public static void main(String[] args) 
{ 
// Create a generic set object of type String. 
   Set<String> s = new HashSet<String>(); 
   int size = s.size(); 
  System.out.println("Size before adding elements: " +size); 
// Adding elements to set. 
   s.add("Orange"); 
   s.add("Red"); 
   s.add("Blue"); 
   s.add("Yellow"); 
   s.add("Green"); 
// Add duplicate elements in tset. These elements will be ignored by set due to not taking duplicate elements. 
   s.add("Red"); 
   s.add("Blue"); 
  System.out.println("Unordered Set Elements"); 
  System.out.println(s); 

// Check 'Black' element is present in the above set or not. 
   if(s.equals("Black"))
   { 
     System.out.println("Black element is not present in set."); 
   } 
  else 
  { 
    s.add("Black"); 
    System.out.println("Black is added successfully."); 
    System.out.println("Set Elements after adding black element"); 
    System.out.println(s); 
   } 
// Create another set object to add collection of elements to the above set. 
   Set<String> s2 = new LinkedHashSet<String>(); 
    s2.add("White"); 
    s2.add("Brown"); 
    s2.add("Red"); // Duplicate element. 
// Call addAll() method to add all the elements of the given collection. 
   s.addAll(s2); 
  System.out.println("Set Element after adding elements from given collection"); 
  System.out.println(s); 
 } 
}
Output: 
       Size before adding elements: 0 
       Unordered Set Elements 
       [Red, Blue, Yellow, Orange, Green] 
       Black is added successfully. 
       Set Elements after adding black element 
       [Red, Blue, Yellow, Black, Orange, Green] 
       Set Element after adding elements from given collection 
       [Red, Brown, White, Blue, Yellow, Black, Orange, Green]

In the above example program, you can observe that set does not maintain the order of elements while storing. It gives unordered collection. When we add duplicate elements in the set, it rejected duplicate elements because the set does not allow duplicate elements (keep in mind these points).

2. Removing an Element from Set: Let’s take a program where we will remove an element from set. We will also check that set is empty or not before adding elements in the list.

Program source code 2:

package setProgram; 
import java.util.HashSet; 
import java.util.Set; 
public class SetExample2 
{ 
public static void main(String[] args) 
{ 
// Create a generic set object of type String. 
   Set<String> s = new HashSet<String>(); 
// Check set is empty or not. 
   boolean check = s.isEmpty(); // Return type of this method is an boolean. 
   System.out.println("Is Set empty: " +check); 

// Adding elements to set. 
   s.add("Orange"); 
   s.add("Red"); 
   s.add("Blue"); 
   s.add("Yellow"); 
   s.add("Green"); 
 if(s.isEmpty())
 { 
  System.out.println("Set is empty."); 
  } 
 else 
 { 
   System.out.println("Set is not empty."); 
   System.out.println("Elements in the Set"); 
   System.out.println(s); 
  } 
// Remove an element from set. 
   s.remove("Blue"); 
   System.out.println("Set elements after removing"); 
   System.out.println(s); 

// Get the total number of set elements. 
   int size = s.size(); 
   System.out.println("Total number of elements: " +size); 
  } 
}
Output: 
       Is Set empty: true 
       Set is not empty. 
       Elements in the Set 
       [Red, Blue, Yellow, Orange, Green] 
       Set elements after removing 
       [Red, Yellow, Orange, Green] 
       Total number of elements: 4

3. Searching an Element in Set: Let’s make a program where we will search an element in set.

Program source code 3:

package setProgram; 
import java.util.HashSet; 
import java.util.Set; 
public class SetExample3 
{ 
public static void main(String[] args) 
{ 
 Set<Character> s = new HashSet<Character>(); 
  s.add('D'); 
  s.add('F'); 
  s.add('H'); 
  s.add('P'); 
  s.add('K'); 
  s.add(null); 
  s.add(null); // Duplicate null element. Therefore, set allow only one null element. 
 System.out.println("Unordered Set Elements"); 
 System.out.println(s); 

// Call contains() method to search an element. 
  boolean search = s.contains('A'); // Returns false because A is not present in the set. 
System.out.println("Is Element A present in set: " +search); 
if(s.contains('K'))
{ 
  System.out.println("K is present in set."); 
 }
else { 
    System.out.println("K is not present in set."); 
 } 
 int hashcode = s.hashCode(); 
 System.out.println("HashCode value: " +hashcode); 
 } 
}
Output: 
       Unordered Set Elements 
       [P, null, D, F, H, K] 
       Is Element A present in set: false 
       K is present in set. 
       HashCode value: 365

When to use Set?


1. If you want to represent a group of individual elements as a single entity where duplicates are not allowed and insertion order is not preserved then we should go for the Set.
2. If your requirement is to get unique elements, set is the best choice for this.
3. If you want to remove duplicate elements without maintaining insertion order from the non-set collection, you should go for set.
Let’s take a simple example program based on the above points.
Program source code 4:
package setProgram; 
import java.util.ArrayList; 
import java.util.HashSet; 
import java.util.List; 
import java.util.Set; 
public class SetExample4 
{ 
public static void main(String[] args) 
{ 
// Create a generic list object of type Integer. 
  List<Integer> list = new ArrayList<Integer>(); 
  int size = list.size(); 
 System.out.println("Size before adding elements: " +size); 
  list.add(5); 
  list.add(10); 
  list.add(5); 
  list.add(15); 
  list.add(20); 
  list.add(10); 
  list.add(20); 
  list.add(30); 
 System.out.println("Original order of List Elements"); 
 System.out.println(list); 
 Set<Integer> s = new HashSet<Integer>(list); 
 System.out.println("Unodered List Elements after removing duplicate."); 
 System.out.println(s); 
 } 
}
Output: 
       Size before adding elements: 0 
       Original order of List Elements 
       [5, 10, 5, 15, 20, 10, 20, 30] 
       Unodered List Elements after removing duplicate
       [20, 5, 10, 30, 15]
Final words 
Hope that this tutorial has covered basic of Set Interface in Java with example programs. In the next tutorial, we will understand how to iterate set in Java.
Thanks for reading!!!

Next ⇒ How to iterate Set in Java⇐ PrevNext ⇒

Leave a Comment