Java HashSet

HashSet class is used to create a collection that uses a hash table for storage. It inherits the AbstractSet class and implements Set interface. HashSet is commonly used if we have to access elements randomly. The hashcode of an element is a unique identity that helps to identify the element in a hash table. HashSet cannot contain duplicate elements. Hence, each hash set element has a unique hashcode.

There are some key points to remember about HashSet:

  1. HashSet stores the elements by using a mechanism called hashing.
  2. HashSet contains unique elements only.
  3. HashSet allows null value.
  4. HashSet class is non synchronized.
  5. HashSet doesn't maintain the insertion order. Here, elements are inserted on the basis of their hashcode.
  6. HashSet is the best approach for search operations.
  7. The initial default capacity of HashSet is 16, and the load factor is 0.75.

Creating a HashSet

In order to create a hash set, we must import the java.util.HashSet package first. Once we import the package, here is how we can create hash sets in Java.


                        Set set = new HashSet();
                                (or)
                        HashSet hashSet = new HashSet();
                    
Creating an HashSet of a specific type

                      // create Integer type hashSet
                      HashSet<Integer> hashSet = new HashSet<Integer>();

                      // create String type hashSet
                      HashSet<String> hashSet = new HashSet<String>();

                      // HashSet with 8 capacity and 0.75 load factor
                      HashSet<Integer> numbers = new HashSet<Integer>(8, 0.75);
                  

Notice, the part new HashSet<>(8, 0.75). Here, the first parameter is capacity, and the second parameter is loadFactor.

  1. capacity - The capacity of this hash set is 8. Meaning, it can store 8 elements.
  2. loadFactor - The load factor of this hash set is 0.75. This means, whenever our hash set is filled by 75%, the elements are moved to a new hash table of double the size of the original hash table.

HashSet constructos

In order to create a HashSet, we need to create an object of the HashSet class. The HashSet class consists of various constructors that allow the possible creation of the HashSet. The following are the constructors available in this class.

Constructor Description Example
HashSet() This constructor is used to build an empty HashSet object in which the default initial capacity is 16 and the default load factor is 0.75. HashSet hs = new HashSet();
HashSet(int initialCapacity) This constructor is used to build an empty HashSet object in which the initialCapacity is specified at the time of object creation. Here, the default loadFactor remains 0.75. HashSet hs = new HashSet(int initialCapacity);
HashSet(int initialCapacity, float loadFactor) This constructor is used to build an empty HashSet object in which the initialCapacity and loadFactor are specified at the time of object creation. HashSet hs = new HashSet(int initialCapacity, float loadFactor);
HashSet(Collection) This constructor is used to build a HashSet object containing all the elements from the given collection. HashSet hs = new HashSet(Collection c);
Methods of HashSet

The HashSet class provides various methods that allow us to perform various operations on the set.

Method Name Description
add() inserts the specified element to the set.
addAll() inserts all the elements of the specified collection to the set.
remove() removes the specified element from the set.
removeAll() removes all the elements from the set.
retainAll() To perform the intersection between two sets, we can use the retainAll() method.
containsAll() To check if a set is a subset of another set or not.
clone() Creates a copy of the HashSet.
contains() Searches the HashSet for the specified element and returns a boolean result.
isEmpty() Checks if the HashSet is empty.
size() Returns the size of the HashSet.
clear() Removes all the elements from the HashSet.
Basic Operations on HashSet

The HashSet class provides various methods to perform different operations on hashset. We will look at some commonly used hashset operations.

  1. ▪ Insert Elements to HashSet
  2. ▪ Access HashSet Elements
  3. ▪ Remove Elements
Set Operations: The various methods of the HashSet class can also be used to perform various set operations.
  1. ▪ Union of Sets
  2. ▪ Intersection of Sets
  3. ▪ Difference of Sets
  4. ▪ Subset

Insert Elements to HashSet

add(), addAll() methods is used to insert elements into HashSet.


                        import java.util.HashSet;

                        public class HashSetInsertExample {
                            public static void main(String[] args) {
                                HashSet<Integer> evenNumber = new HashSet<Integer>();

                                // Using add() method
                                evenNumber.add(2);
                                evenNumber.add(4);
                                evenNumber.add(6);
                                System.out.println("HashSet: " + evenNumber);

                                HashSet<Integer> numbers = new HashSet<Integer>();
                                
                                // Using addAll() method
                                numbers.addAll(evenNumber);
                                numbers.add(5);
                                System.out.println("New HashSet: " + numbers);
                            }
                        }
                    
Access HashSet Elements

To access the elements of a hash set, we can use the iterator() method. In order to use this method, we must import the java.util.Iterator package.


                        import java.util.HashSet;
                        import java.util.Iterator;

                        public class HashSetAccessExample {
                            public static void main(String[] args) {
                                HashSet<Integer> numbers = new HashSet<Integer>();
                                numbers.add(2);
                                numbers.add(5);
                                numbers.add(6);
                                System.out.println("HashSet: " + numbers);

                                // Calling iterator() method
                                Iterator<Integer> iterate = numbers.iterator();
                                System.out.print("HashSet using Iterator: ");
                                // Accessing elements
                                while(iterate.hasNext()) {
                                    System.out.println(iterate.next());
                                }

                                // using for-each
                                for (int value: hashSet) {
                                  System.out.println(value);
                              }
                            }
                        }

                    
Remove Elements

remove(), removeAll() methods are used to remove specified element or all the elements from the HashSet collection.


                        import java.util.HashSet;

                        public class HashSetRemove {
                            public static void main(String[] args) {
                                HashSet<Integer> numbers = new HashSet<>();
                                numbers.add(2);
                                numbers.add(5);
                                numbers.add(6);
                                System.out.println("HashSet: " + numbers);

                                // Using remove() method
                                boolean value1 = numbers.remove(5);
                                System.out.println("Is 5 removed? " + value1);

                                boolean value2 = numbers.removeAll(numbers);
                                System.out.println("Are all elements removed? " + value2);
                            }
                        }
                    
Union of Sets

To perform the union between two sets, we can use the addAll() method. For example:


                        import java.util.HashSet;

                        public class UnionOfSetExample {
                            public static void main(String[] args) {
                                HashSet<Integer> evenNumbers = new HashSet<>();
                                evenNumbers.add(2);
                                evenNumbers.add(4);
                                System.out.println("HashSet1: " + evenNumbers);

                                HashSet<Integer> numbers = new HashSet<>();
                                numbers.add(1);
                                numbers.add(3);
                                System.out.println("HashSet2: " + numbers);

                                // Union of two set
                                numbers.addAll(evenNumbers);
                                System.out.println("Union is: " + numbers);
                            }
                        }
                    
Intersection of Sets

To perform the intersection between two sets, we can use the retainAll() method. For example:


                        import java.util.HashSet;

                        public class IntersectionOfSetsExample {
                            public static void main(String[] args) {
                                HashSet<Integer> primeNumbers = new HashSet<>();
                                primeNumbers.add(2);
                                primeNumbers.add(3);
                                System.out.println("HashSet1: " + primeNumbers);

                                HashSet<Integer> evenNumbers = new HashSet<>();
                                evenNumbers.add(2);
                                evenNumbers.add(4);
                                System.out.println("HashSet2: " + evenNumbers);

                                // Intersection of two sets
                                evenNumbers.retainAll(primeNumbers);
                                System.out.println("Intersection is: " + evenNumbers);
                            }
                        }

                    
Difference of Sets

To calculate the difference between the two sets, we can use the removeAll() method. For example:


                        import java.util.HashSet;

                        public class DifferenceOfSets {
                            public static void main(String[] args) {
                                HashSet<Integer> primeNumbers = new HashSet<>();
                                primeNumbers.add(2);
                                primeNumbers.add(3);
                                primeNumbers.add(5);
                                System.out.println("HashSet1: " + primeNumbers);

                                HashSet<Integer> oddNumbers = new HashSet<>();
                                oddNumbers.add(1);
                                oddNumbers.add(3);
                                oddNumbers.add(5);
                                System.out.println("HashSet2: " + oddNumbers);

                                // Difference between HashSet1 and HashSet2
                                primeNumbers.removeAll(oddNumbers);
                                System.out.println("Difference : " + primeNumbers);
                            }
                        }
                    
Subset

To check if a set is a subset of another set or not, we can use the containsAll() method. For example:


                        import java.util.HashSet;

                        public class SubsetsExample {
                            public static void main(String[] args) {
                                HashSet<Integer> numbers = new HashSet<>();
                                numbers.add(1);
                                numbers.add(2);
                                numbers.add(3);
                                numbers.add(4);
                                System.out.println("HashSet1: " + numbers);

                                HashSet<Integer> primeNumbers = new HashSet<>();
                                primeNumbers.add(2);
                                primeNumbers.add(3);
                                System.out.println("HashSet2: " + primeNumbers);

                                // Check if primeNumbers is a subset of numbers
                                boolean result = numbers.containsAll(primeNumbers);
                                System.out.println("Is HashSet2 is subset of HashSet1? " + result);
                            }
                        }