HashSet in Java

HashSet

In the previous blog, we learned about the Concrete Collection in Java. If you want to know more about it visit Concrete Collections in Java - LinkedList . In this blog we will go through another Class in Collection called HashSet.


HashSet

In our previous blog, we have already seen that the LinkedList and array stored the elements in a sequential manner as per our convenience. But the drawback is that if we are trying to search for a particular element and we don’t remember the index position of that element then we need to visit through all the elements until we find that element. This task is time-consuming. But if we don’t care about the sequencing of the element, then there are data structures that can solve this problem and help to find the element much faster than LinkedList and array. The well known data structure that finds the elements quickly is called Hash Table. The hash table functionality is provided by the Class in the Collection Framework called HashSet. In order to create a HashSet, the first step we need to perform is to import the package java.util.HashSet.


Syntax of Creating a HashSet

Once the package is imported we can create the HashSet in the following way:

Syntax

HashSet<Type> numbers = new HashSet<>();

Here the Type specifies the Type of the HashSet

e.g.

HashSet<String> str = new HashSet<>();
HashSet<Interger> nos = new HashSet<>();

Importance of HashSet

We have already seen above that HashSet is mostly used when we want to access the elements randomly. The reason is that the elements in the hash table are accessed using the hash code. As the hash codes are unique in nature, the HashSet cannot contain duplicate elements.


Methods of HashSet

HashSet provides various methods that allow us to perform operations on Sets. We will go through those methods one by one

  1. add()
  2. add() method adds the specified element to the set if that element is not present in the Set.

    e.g.

    import java.util.HashSet;
    class HashSetAddEx {
      public static void main(String[] args) {
        HashSet<String> days = new HashSet<>();
        // Using add() method
        days.add("Sunday");
        days.add("Monday");
        days.add("Tuesday");
        System.out.println("HashSet: " + days);
      }
    }

    Output

    HashSet: [Monday, Sunday, Tuesday]
  3. addAll()
  4. addAll() method is used for adding all the specified elements of the collection to the Set.

    e.g.

    import java.util.HashSet;
    class HashSetAddAllEx {
      public static void main(String[] args) {
        HashSet<String> days = new HashSet<>();
      // Using add() method
        days.add("Sunday");
        days.add("Monday");
        days.add("Tuesday");
        System.out.println("HashSet: " + days);
      //Using addAll() method
        HashSet<String> daysOfWeek = new HashSet<>();
        daysOfWeek.addAll(days);
        daysOfWeek.add("Wednesday");
        daysOfWeek.add("Thursday");
        daysOfWeek.add("Friday");
        daysOfWeek.add("Saturday");
        System.out.println("HashSet After adding the new elements: " + daysOfWeek);
      }
    }

    Output

    HashSet: [Monday, Sunday, Tuesday]
    HashSet After adding the new elements: [Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]
  5. iterator()
  6. iterator() method is used to access the elements of the hash set.

    e.g.

    import java.util.HashSet;
    import java.util.Iterator;
    class HashSetIteratorEx {
      public static void main(String[] args) {
        HashSet<String> days = new HashSet<>();
      // Using add() method
        days.add("Sunday");
        days.add("Monday");
        days.add("Tuesday");
        System.out.println("HashSet: " + days);
      //Using addAll() method
        HashSet<String> daysOfWeek = new HashSet<>();
        daysOfWeek.addAll(days);
        daysOfWeek.add("Wednesday");
        daysOfWeek.add("Thursday");
        daysOfWeek.add("Friday");
        daysOfWeek.add("Saturday");
        System.out.println("HashSet After adding the new elements: " + daysOfWeek);
        System.out.println("Displaying HashSet using Iterator : ");
        for (Iterator itr = daysOfWeek.iterator(); itr.hasNext();) {
          System.out.println(itr.next());
        }
      }
    }

    Output

    HashSet: [Monday, Sunday, Tuesday]
    HashSet After adding the new elements: [Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]
    
    Displaying HashSet using Iterator:
    MondayThursday
    Friday
    Sunday
    Wednesday
    Tuesday
    Saturday
  7. remove()
  8. remove() method is used to remove or delete the specified element from the Set.

    e.g.

    import java.util.HashSet;
    class HashSetRemoveEx {
      public static void main(String[] args) {
        HashSet<String> days = new HashSet<>();
      // Using add() method
        days.add("Sunday");
        days.add("Monday");
        days.add("Tuesday");
        System.out.println("HashSet: " + days);
      //Using addAll() method
        HashSet<String> daysOfWeek = new HashSet<>();
        daysOfWeek.addAll(days);
        daysOfWeek.add("Wednesday");
        daysOfWeek.add("Thursday");
        daysOfWeek.add("Friday");
        daysOfWeek.add("Saturday");
        System.out.println("HashSet After adding the new elements: " + daysOfWeek);
        System.out.println("Removing the element: " + daysOfWeek.remove("Monday"));
        System.out.println("HashSet After removing the element: " + daysOfWeek);
      }
    }

    Output

    HashSet: [Monday, Sunday, Tuesday]
    HashSet After adding the new elements: [Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]
    Removing the element: true
    HashSet After removing the element: [Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]
  9. remove()
  10. remove() methods removes or deletes all the elements of the set.

    e.g.

    import java.util.HashSet;
    class HashSetremoveAllEx {
      public static void main(String[] args) {
        HashSet<String> days = new HashSet<>();
      // Using add() method
        days.add("Sunday");
        days.add("Monday");
        days.add("Tuesday");
        System.out.println("HashSet: " + days);
      //Using addAll() method
        HashSet<String> daysOfWeek = new HashSet<>();
        daysOfWeek.addAll(days);
        daysOfWeek.add("Wednesday");
        daysOfWeek.add("Thursday");
        daysOfWeek.add("Friday");
        daysOfWeek.add("Saturday");
        System.out.println("HashSet After adding the new elements: " + daysOfWeek);
        System.out.println("Are all the elements deleted from the HashSet: " + daysOfWeek.removeAll(daysOfWeek));
      }
    }

    Output

    HashSet: [Monday, Sunday, Tuesday]
    HashSet After adding the new elements: [Monday, Thursday, Friday, Sunday, Wednesday, Tuesday, Saturday]
    Are all the elements deleted from the HashSet: true
  11. retainAll()
  12. retainAll() is used when we want to perform set operations i.e. intersection. It performs the intersection between the two sets.

    e.g.

    import java.util.HashSet;
    class HashSetRetainAllEx {
      public static void main(String[] args) {
          HashSet<Integer> nos = new HashSet<>();
        // Using add() method
          nos.add(10);
          nos.add(20);
          nos.add(30);
          System.out.println("HashSet1: " + nos);
        //Using addAll() method
          HashSet<Integer> nos1 = new HashSet<>();
          nos1.add(70);
          nos1.add(90);
          nos1.add(30);
          System.out.println("HashSet2: " + nos1);
          nos1.retainAll(nos);
          System.out.println("Intersection between two HashSets " + nos1);
      }
    }

    Output

    HashSet1: [20, 10, 30]
    HashSet2: [70, 90, 30]
    Intersection between two HashSets [30]
  13. containsAll()
  14. containsAll() method is used to verify whether the set is a subset of another set or not.

    e.g.

    import java.util.HashSet;
    class HashSetContainsAllEx {
      public static void main(String[] args) {
        HashSet<Integer> nos = new HashSet<>();
      // Using add() method
        nos.add(10);
        nos.add(20);
        nos.add(30);
        System.out.println("HashSet1: " + nos);
      //Using addAll() method
        HashSet<Integer> nos1 = new HashSet<>();
        nos1.add(20);
        nos1.add(30);
        System.out.println("HashSet2 " + nos1);
        System.out.println("Is HashSet2 subset of Hash1: " + nos.containsAll(nos1));
      }
    }

    Output

    HashSet1: [2, 3]
    HashSet2: [2, 4]
    Intersection is: true
  15. contains()
  16. contains() method searches or finds the HashSet for the specified elements and returns the result either true or false.

  17. clone()
  18. clone() method is used to create a copy of the HashSet.

  19. clear()
  20. clear() method is used to remove or delete all the elements of the HashSet

  21. size()
  22. size() method returns the size of the HashSet.

  23. isEmpty()
  24. isEmpty() method is used for checking whether the HashSet is empty or not.

    Example of the above methods:

    e.g.

    import java.util.HashSet;
    class HashSetMethodsEx {
      public static void main(String[] args) {
        HashSet<Integer> nos = new HashSet<>();
      // Using add() method
        nos.add(10);
        nos.add(20);
        nos.add(30);
        System.out.println("HashSet1: " + nos);
      //Using addAll() method
        HashSet<Integer> nos1 = new HashSet<>();
        nos1.add(20);
        nos1.add(30);
        System.out.println("HashSet2 " + nos1);
      //Using contains() method
        System.out.println("Is HashSet1 and  HashSet2 contains the mentioned element: " + nos.contains(20));
      //Using clone() method
        System.out.println("Clone HashSet1" + nos.clone());
        System.out.println("Clone HashSet2" + nos1.clone());
      //Using size() method
        System.out.println("Size of HashSet1:" + nos1.size());
        System.out.println("Size of HashSet1:" + nos.size());
      //Using clear() method
        nos.clear();
        System.out.println(" HashSet1:" +nos );
      //Using isEmpty() method
        System.out.println("Is HashSet1 empty:" + nos.isEmpty());
      }
    }

    Output

    HashSet1: [20, 10, 30]
    HashSet2 [20, 30]
    Is HashSet1 and  HashSet2 contains the mentioned element: true
    Clone HashSet1[10, 20, 30]
    Clone HashSet2[20, 30]
    Size of HashSet1:2
    Size of HashSet1:3
    HashSet1:[]
    Is HashSet1 empty:true

Core Java Tutorial

Get in Touch

Atrowel will be pleased to receive your feedback and suggestions. Those of you who would like to contribute, please send us an email.