HashSet in Java With Examples

HashSet in Java implements the Set interface and inherits the AbstractSet class. HashSet class is used to store the collection of unique elements.

HashSetClassHierarchy

FewΒ important points about Java HashSet class are:

  • HashSet stores the elements by using hashing technique.
  • HashSetΒ  only contains unique elements.
  • HashSetΒ  can allows null value.
  • HashSet class is non synchronized in nature.
  • HashSet doesn’t maintain the order of insertion. In this, elements are inserted on the basis of their hashcode value.
  • HashSet implements Serializable and Cloneable interface.
  • The initial default capacity of HashSet is 16 and the load factor is 0.75.

Initial Capacity:Β The initial capacity means the number of bucketsΒ  are available when hashtable (HashSet internally uses hashtable data structure) isΒ  initially created. The number of available buckets will be automatically increased if the current size starts getting full.

Load Factor:Β The load factor is a measure of how much full the HashSet is allowed before getting its capacity automatically increased. When the number of items in the hash table exceeds the product of the load factor and the current capacity then the hash table is rehashed to increase the hashtable twice the number of buckets.

Load factor and initial capacity are two prime factors which affects the performance of HashSet.Β For reducing the rehashing operation we must choose initial capacity very wisely . If initial capacity is more than the maximum number of entries divided by the load factor then no rehashing will be done.

Constructors in HashSet:

  1. HashSet h = new HashSet();Β 
    Default initial capacity is 16 and load factor is 0.75.
  2. HashSet h = new HashSet(int initialCapacity);Β 
  3. HashSet h = new HashSet(int initialCapacity, float loadFactor);
  4. HashSet h = new HashSet(Collection C);

Internal working of a HashSet and Storage

HashSet uses HashMap for storing its elements internally. While in HashMap we need a key-value pair, but in HashSet we are passing value only.

In fact the value we insert in HashSet works as a key to the map Object and for its value java uses a constant value. Therefore in key-value pair all the keys will have same value.

Creating a HashSet and adding Elements in it

import java.util.*; 
class HashSetExample{ 
public static void main(String args[]){ 
//Creating HashSet and adding elements 
HashSet<String> set=new HashSet(); 
set.add("One"); 
set.add("Two"); 
set.add("Three"); 
set.add("Four"); 
set.add("Five"); 
Iterator<String> i=set.iterator(); 
while(i.hasNext()) 
{ 
System.out.println(i.next()); 
} 
} 
} 

Output:-
Five
One
Four
Two
Three

Java HashSet example Removing duplicate elements

import java.util.*; 
class HashSetExample{ 
public static void main(String args[]){ 
//Creating HashSet and adding elements 
HashSet<String> set=new HashSet<String>(); 
set.add("Ram"); 
set.add("Shyam"); 
set.add("Ram"); 
set.add("Anil"); 
//Traversing elements 
Iterator<String> itr=set.iterator(); 
while(itr.hasNext()){ 
System.out.println(itr.next()); 
} 
} 
} 
Output:-
Shyam
Ram
Anil

Iterating over a HashSet

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

public class HashSetExample {
public static void main(String[] args) {
Set<String> programmingLanguages = new HashSet<>();
programmingLanguages.add("C++");
programmingLanguages.add("C");
programmingLanguages.add("Java");
programmingLanguages.add("Python");
programmingLanguages.add("PHP");

System.out.println("=== Iterate over a HashSet using Java 8 forEach and lambda ===");
programmingLanguages.forEach(programmingLanguage -> {
System.out.println(programmingLanguage);
});

System.out.println("=== Iterate over a HashSet using iterator() ===");
Iterator<String> programmingLanguageIterator = programmingLanguages.iterator();
while (programmingLanguageIterator.hasNext()) {
String programmingLanguage = programmingLanguageIterator.next();
System.out.println(programmingLanguage);
}

System.out.println("=== Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method ===");
programmingLanguageIterator = programmingLanguages.iterator();
programmingLanguageIterator.forEachRemaining(programmingLanguage -> {
System.out.println(programmingLanguage);
});

System.out.println("=== Iterate over a HashSet using simple for-each loop ===");
for(String programmingLanguage: programmingLanguages) {
System.out.println(programmingLanguage);
}
}
}

Output:-

=== Iterate over a HashSet using Java 8 forEach and lambda ===
Java
C++
C
PHP
Python
=== Iterate over a HashSet using iterator() ===
Java
C++
C
PHP
Python
=== Iterate over a HashSet using iterator() and Java 8 forEachRemaining() method ===
Java
C++
C
PHP
Python
=== Iterate over a HashSet using simple for-each loop ===
Java
C++
C
PHP
Python

 

Java HashSet from another Collection

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

public class HashSetExample { 
public static void main(String args[]){ 
ArrayList<String> list=new ArrayList<String>(); 
list.add("Ram"); 
list.add("Shyam"); 
list.add("Anil"); 

HashSet<String> set=new HashSet(list); 
set.add("Gaurav"); 
Iterator<String> i=set.iterator(); 
while(i.hasNext()) 
{ 
System.out.println(i.next()); 
} 
} 
}

Output:-
Shyam
Gaurav
Ram
Anil

 

HashSet with User defined objects

import java.util.Comparator;
import java.util.Objects;
import java.util.SortedSet;
import java.util.TreeSet;

class Employee implements Comparable<Employee> {
private int id;
private String name;

public Employee(int id, String name) {
this.id = id;
this.name = name;
}

public int getId() {
return id;
}

public void setId(int id) {
this.id = id;
}

public String getName() {
return name;
}

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

// Two Employees are equal if their IDs are equal
@Override
public boolean equals(Object o) {
if (this == o) return true;
if (o == null || getClass() != o.getClass()) return false;
Employee employee = (Employee) o;
return id == employee.id;
}

@Override
public int hashCode() {
return Objects.hash(id);
}

// Compare employees based on their IDs
@Override
public int compareTo(Employee employee) {
return this.getId() - employee.getId();
}

@Override
public String toString() {
return "Employee{" +
"id=" + id +
", name='" + name + '\'' +
'}';
}
}

HashSet implementation Class:

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

public class HashSetExample{
public static void main(String[] args) {
Set<Employee> employee = new HashSet<>();
employee.add(new Employee(101, "Ashish"));
employee.add(new Employee(102, "Rahul"));
employee.add(new Employee(103, "Ram"));

/*
HashSet will use the `equals()` & `hashCode()` implementations 
of the Customer class to check for duplicates and ignore them
*/
employee.add(new Employee(101, "Ashish"));

System.out.println(employee);
}
}

Output:-

[Employee{id=101, name='Ashish'}, Employee{id=102, name='Rahul'}, Employee{id=103, name='Ram'}]

 

Conclusion

We have learnt about what is HashSet and their extending class. We have created the Simple HashSet and added elements to it.

You have seen example of adding elements to HashSet from other Collection. You have practiced how to iterate over a HashSet and how to create a HashSet of user defined objects.

Newsletter Updates

Enter your name and email address below to subscribe to our newsletter

Leave a Reply