HashSet Java

Hey there!! Welcome to flower brackets blog. In this post we are going to learn hashset java.

Introduction: hashset java

HashSet Java

Here you can see hierarchy of hashset class. Hashset class extends abstractset class. AbstractSet class implements set interface.

And set interface extends collection interface. Collection interface extends iterable interface.


java.util

Class HashSet<E>

java.lang.Object
     java.util.AbstractCollection<E>
          java.util.AbstractSet<E>
               java.util.HashSet<E>

Parameters

E - type of elements maintained by this set.

Implemented Interfaces

Serializable, Cloneable, Iterable<E>, Collection<E>, Set<E>

Subclasses

JobStateReasons, LinkedHashSet

The class that hashset class belongs to is java.util package. Here letter “E” is nothing but type of elements which we can add it to the hashset.

The type can be string or integer or employee object or user object etc. and hashset which extends abstractset.

Also Read – Sort Hashmap By Value

Abstractset extends abstractcollection and abstractcollection extends object.

Next you can see some of the implemented interfaces like serializable, cloneable, iterable, collection and set.

Moving on subclasses of hashset are jobstatereasons and linkedhashset.


What is hashset in java?

Hashset is a collection. It won’t allow duplicate elements. It means hashset contains only unique elements and hashset is an unordered collection.

Hashset would maintain insertion order and in hashset we can add null element.

Also Read – ArrayList Java

And hashset is not synchronized. Hashset class implements set interface and it is backed up by hash table.

Hashset class offers constant time performance for basic operations like add, remove, contains and size.

It makes no assurance as to the iteration order of the set. That is, there is no guarantee that the order will remain constant over time.

Also Read – Java Treeset

Because underlying data structure for hashset is hashtable. So in usual case time complexity for basic operations like add, remove, contains and size hashset takes big O of one time, that is, O(1) time.

Declaration – hashset class

public class HashSet<E> extends AbstractSet<E> implements Set<E>, Cloneable, Serializable

Hashset class methods

MethodsDescription
boolean add ( E e )adds the specified element to this set if it is not already present
void clear ( )removes all of the elements from this set.
Object clone ( )returns a shallow copy of this HashSet instance: the elements themselves are not cloned.
boolean contains ( Object o )returns true if this set contains the specified element.
boolean isEmpty ( )method used to check whether the set is empty or not. Returns true if this set contains no elements and false for non-empty condition.
Iterator iterator()returns an iterator over the elements in this set.
boolean remove ( Object o )removes the specified element from this set if it is present.
int size ( )returns the number of elements in this set ( its cardinality ).

Below are some of the methods inherited

Methods inherited from class java.util.AbstractSet
removeAll, equals, hashCode

Methods inherited from class java.util.AbstractCollection
retainAll, addAll, containsAll, toArray, toString, toArray

Methods inherited from class java.lang.Object
wait, notifyAll, notify, finalize, getClass, wait, wait

Methods inherited from interface java.util.Set
toArray, retainAll, removeAll, hashCode, equals, containsAll, addAll, toArray


Hashset java example : hashset java

import java.util.HashSet;

public class HashsetExample
{
   public static void main(String[] args)
   {
      // here's hashset declaration
      HashSet<String> hs = new HashSet<String>();

      // adding elements
      hs.add("orange");
      hs.add("mango");
      hs.add("strawberry");
      hs.add("cherry");
      hs.add("apple");
      hs.add("banana");

      // now adding duplicate values to hashset
      hs.add("orange");
      hs.add("mango");

      // now adding null values to hashset
      hs.add(null);
      hs.add(null);

      // finally printing hashset elements
      System.out.println("---------- HashSet Example in java ------------------");
      System.out.println("Displaying hashset elements : " + hs);
   }
}

Output:

HashSet Java


Hashset constructor

Here we are going to discuss hashset constructor. Below is the first default constructor,

public HashSet()

Using above constructor we can construct new empty HashSet with the initial capacity 16 and load factor 0.75

This is the second HashSet constructor which accepts initialCapacity,

public HashSet(int initialCapacity)

Suppose say initial capacity is 5 then above constructor will construct empty HashSet with initial capacity 5 and load factor 0.75

Next comes the third HashSet constructor which accepts initialCapacity and loadFactor,

public HashSet(int initialCapacity, float loadFactor)

Suppose say initial capacity is 5 and load factor is 1.25 then above constructor will create empty HashSet with initial capacity 5 and load factor 1.25.

Also Read – Random Number Generator Java

The final HashSet constructor is as follows. This HashSet constructor accepts Collection (Collection can be ArrayList or LinkedList or Set).

public HashSet(Collection<? extends E> c)

Suppose say in Collection there are three objects and if we pass Collection to above HashSet constructor what happens is above HashSet constructor will create a new HashSet and it will contain whatever elements present in the Collection.


Example on hashset constructor

To explain java hashset constructor example I have created a java program,

import java.util.HashSet;

public class HashsetConstructor 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();

      // adding string objects
      hs.add("Bret");
      hs.add("Adam");
      hs.add("Sasha");
      hs.add("Peter");
      hs.add("William");

      System.out.println("Hashset java example : " + hs + "\n");
   }
}

Output :

Hashset java example : [Bret, Adam, Sasha, Peter, William]


Hashset constructor accepts collection

In this segment we will learn hashset constructor which accepts collection. To understand this let’s see a java program,

// HashSet(Collection<? extends E> c) constructor example

import java.util.HashSet;
import java.util.LinkedList;

public class HashsetCollectionDemo 
{
   public static void main(String[] args) 
   {
      LinkedList<Integer> li = new LinkedList<Integer>();

      // adding three integer objects
      li.add(500);
      li.add(1000);
      li.add(1500);

      System.out.println("Linkedlist example : " + li + "\n");

      HashSet<Integer> hs = new HashSet<Integer>(li);
      System.out.println("Hashset collection example : " + hs + "\n");
   }
}

Output :

Linkedlist example : [500, 1000, 1500]

Hashset collection example : [500, 1000, 1500]


How to create hashset from another collection

Now let’s learn how to create hashset from another collection using HashSet(Collection) constructor,

import java.util.ArrayList;
import java.util.HashSet;
import java.util.List;
import java.util.Set;

public class HashsetCollectionExample 
{
   public static void main(String[] args) 
   {
      List<Integer> liEven = new ArrayList<>();
      liEven.add(2);
      liEven.add(4);
      liEven.add(6);
      liEven.add(8);
      liEven.add(10);

      List<Integer> liOdd = new ArrayList<>();
      liOdd.add(1);
      liOdd.add(3);
      liOdd.add(5);
      liOdd.add(7);
      liOdd.add(9);

      // here we are creating a hashset from another collection, i.e, ArrayList
      Set<Integer> setAll = new HashSet<>(liEven);

      // here we add all the elements from existing collection to hashset
      setAll.addAll(liOdd);

      System.out.println("Hashset collection example : " + setAll);
   }
}

Output :

Hashset collection example : [1, 2, 3, 4, 5, 6, 7, 8, 9, 10]


Java hashsets operations

In this segment let’s learn how to check hashset is empty or not using an example,

import java.util.HashSet;

public class HashsetIsEmptyDemo 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      System.out.println("Hashset : " + hs);
      boolean checkEmpty = hs.isEmpty();
      System.out.println("Checking for empty : " + checkEmpty + "\n");
      hs.add("Sachin");
      hs.add("Virat");
      hs.add("Dhoni");
      hs.add("Rohit");
      System.out.println("Hashset : " + hs);
      checkEmpty = hs.isEmpty();
      System.out.println("Checking for empty : " + checkEmpty + "\n");
      // here we are finding size of hashset
      System.out.println("Number of Players in hashset : " + hs.size());
      // here we are checking element is there are not
      String player = "Dhoni";
      if(hs.contains(player))
      {
         System.out.println(player + " is in the players list.");
      }
      else
      {
         System.out.println(player + " is not in the players list.");
      }
   }
}

Output :

Hashset : [ ]
Checking for empty : true

Hashset : [Rohit, Dhoni, Sachin, Virat]
Checking for empty : false

Number of Players in hashset : 4
Dhoni is in the players list.


How to remove object from hashset?

Let’s learn how to remove object from hashset using a sample java program,

import java.util.HashSet;

public class HashsetRemoveDemo 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Sachin");
      hs.add("Virat");
      hs.add("Dhoni");
      hs.add("Rohit");
      System.out.println("Hashset example : " + hs + "\n");

      // removing element from hashset using remove() method
      boolean checkRemove = hs.remove("Rohit");
      System.out.println("Checking if string is removed : " + checkRemove + "\n");
      System.out.println("After removing string Rohit : " + hs);
   }
}

Output :

Hashset example : [Rohit, Dhoni, Sachin, Virat]

Checking if string is removed : true

After removing string Rohit : [Dhoni, Sachin, Virat]


How to remove group of objects from hashset?

Here i’m going to cover how to remove group of objects from hashset. Let’s see a simple java program,

import java.util.ArrayList;
import java.util.HashSet;

public class HashsetRemoveAll 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Sindhu");
      hs.add("Srikanth");
      hs.add("Saina");
      hs.add("Gopichand");

      System.out.println("HashSet example : " + hs + "\n");

      ArrayList<String> al = new ArrayList<String>();
      al.add("Sindhu");
      al.add("Virat");
      al.add("Saina");
      al.add("Sachin");

      System.out.println("Arraylist : " + al + "\n");

      boolean checkRemove = hs.removeAll(al);

      System.out.println("Checking if string is removed : " + checkRemove);
      System.out.println("HashSet example : " + hs);
   }
}

Output :

HashSet example : [Saina, Sindhu, Srikanth, Gopichand]

Arraylist : [Sindhu, Virat, Saina, Sachin]

Checking if string is removed : true
HashSet example : [Srikanth, Gopichand]


Java iterate over hashset

Now let us learn using iterator how to get each element from the hashset. Let me explain using a simple java program,

// Iterating over a HashSet using iterator()

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

public class HashsetIteratorDemo 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Sachin");
      hs.add("Virat");
      hs.add("Dhoni");
      hs.add("Rohit");
      hs.add("Yuvraj");
      System.out.println("HashSet example : " + hs + "\n");

      // returns iterator over elements and the elements will have no proper order
      Iterator<String> iterate = hs.iterator();

      // this while loop uses "iterate" to get each element from hashset
      while(iterate.hasNext())
      {
         String player = iterate.next();
         System.out.println(player);
      }
   }
}

Output :

HashSet example : [Rohit, Yuvraj, Dhoni, Sachin, Virat]

Rohit
Yuvraj
Dhoni
Sachin
Virat


Iterating over a HashSet using foreach

import java.util.HashSet;

public class HashsetIteratorDemo 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Sachin");
      hs.add("Virat");
      hs.add("Dhoni");
      hs.add("Rohit");
      hs.add("Yuvraj");
      System.out.println("HashSet example : " + hs + "\n");

      System.out.println("Iterating over a HashSet using foreach : ");
      for(String name : hs)
      {
         System.out.println(name);
      }
   }
}

Output :

HashSet example : [Rohit, Yuvraj, Dhoni, Sachin, Virat]

Iterating over a HashSet using foreach :
Rohit
Yuvraj
Dhoni
Sachin
Virat


Iterating over a HashSet using iterator() and forEachRemaining() method

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

public class HashsetIteratorDemo 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Sachin");
      hs.add("Virat");
      hs.add("Dhoni");
      hs.add("Rohit");
      hs.add("Yuvraj");
      System.out.println("HashSet example : " + hs + "\n");

      Iterator<String> iterate = hs.iterator();
      System.out.println("Iterating over a HashSet using iterator() and forEachRemaining() method : ");
      iterate = hs.iterator();
      iterate.forEachRemaining(players -> 
      {
         System.out.println(players);
      });
   }
}

Output :

HashSet example : [Rohit, Yuvraj, Dhoni, Sachin, Virat]

Iterating over a HashSet using iterator() and forEachRemaining() method :
Rohit
Yuvraj
Dhoni
Sachin
Virat


Iterating over a HashSet using forEach and lambda

import java.util.HashSet;

public class HashsetIteratorDemo 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Sachin");
      hs.add("Virat");
      hs.add("Dhoni");
      hs.add("Rohit");
      hs.add("Yuvraj");
      System.out.println("HashSet example : " + hs + "\n");

      System.out.println("Iterating over a HashSet using forEach and lambda : ");
      hs.forEach(players -> 
      {
         System.out.println(players);
      });
   }
}

Output :

HashSet example : [Rohit, Yuvraj, Dhoni, Sachin, Virat]

Iterating over a HashSet using forEach and lambda :
Rohit
Yuvraj
Dhoni
Sachin
Virat


How to remove all elements from the hashset?

Let’s learn using a simple java program,

import java.util.HashSet;

public class HashsetClearDemo 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Sachin");
      hs.add("Virat");
      hs.add("Dhoni");
      hs.add("Rohit");
      hs.add("Yuvraj");
      System.out.println("HashSet example : " + hs + "\n");

      // clear method removes all elements from hashset
      hs.clear();
      System.out.println("Hashset clear method : " + hs);
   }
}

Output :

HashSet example : [Rohit, Yuvraj, Dhoni, Sachin, Virat]

Hashset clear method : [ ]


Add user defined objects in the hashset

Let’s learn how to add user defined objects in the hashset using a sample java program,

// Employee class

public class Employee 
{
   private String name;
   private int age;
   private int ID;

   public Employee(String name, int age, int ID)
   {
      super();
      this.name = name;
      this.age = age;
      this.ID = ID;
   }

   public String getName()
   {
      return name;
   }

   public void setName(String name)
   {
      this.name = name;
   }

   public int getAge()
   {
      return age;
   }

   public void setAge(int age)
   {
      this.age = age;
   }

   public int getID()
   {
      return ID;
   }

   public void setID(int ID)
   {
      this.ID = ID;
   }

   @Override
   public String toString() 
   { 
      return "Employee [name = " + name + ", age = " + age + ", ID = " + ID + "]";
   }
}

// main class

import java.util.HashSet;

public class UserDefinedHashsetExample 
{
   public static void main(String[] args) 
   {
      HashSet<Employee> hs = new HashSet<Employee>();

      Employee kate = new Employee("kate", 23, 10014);
      Employee prince = new Employee("prince", 25, 10015);
      Employee bret = new Employee("bret", 28, 10016);

      hs.add(kate);
      hs.add(prince);
      hs.add(bret);

      System.out.println("HashSet example : " + hs + "\n");

      // we are using for each loop to get employee object from hashset

      for(Employee emp : hs)
      {
         System.out.println("User defined objects in the hashset : ");
         System.out.println(emp.toString());
         System.out.println("Employee name : " + emp.getName());
         System.out.println("Employee age : " + emp.getAge());
         System.out.println("Employee ID : " + emp.getID());
      }
   }
}

Output :

HashSet example : [Employee [name = bret, age = 28, ID = 10016], Employee [name = kate, age = 23, ID = 10014], 
Employee [name = prince, age = 25, ID = 10015]]

User defined objects in the hashset : 
Employee [name = bret, age = 28, ID = 10016]
Employee name : bret
Employee age : 28
Employee ID : 10016
User defined objects in the hashset : 
Employee [name = kate, age = 23, ID = 10014]
Employee name : kate
Employee age : 23
Employee ID : 10014
User defined objects in the hashset : 
Employee [name = prince, age = 25, ID = 10015]
Employee name : prince
Employee age : 25
Employee ID : 10015


conclusion

So this is about hashset java collection framework. I hope you have understood the concept.

You can subscribe to my blog flower brackets if you haven’t already.


Reference – Oracle help centre

You May Also Like