HashSet in java

Let’s learn hashset in java.

HashSet in java

  • underlying data structure for HashSet is hashtable.
  • HashSet implements Set interface.
  • Hashset does not allow duplicate elements. If any duplicate object is added, then add() method returns “false” without adding any duplicate object.
  • Object are inserted based on their hash code.
  • Hashset does not maintain or preserve insertion order.
  • In hashset heterogeneous elements are allowed.
  • Hashset allow “null” value.
  • Hashset implements Serializable and Cloneable interface.
  • In hashset, searching objects is easier. Because objects are stored based on hashcode.
  • HashSet do not implement RandomAccess interface.

Let’s see java hashset example.

import java.util.HashSet;
import java.util.Iterator;
public class HashSetExample
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<>();
      hs.add("Banana");
      hs.add("Orange");
      hs.add("Apple");
      hs.add("Pineapple");
      hs.add("Mango");
      Iterator<String> ir = hs.iterator();
      while(ir.hasNext())
      {
         System.out.println(ir.next());
      }
   }
}


Output:

Apple
Mango
Pineapple
Orange
Banana


Initial capacity : is initial number of buckets that a Hashset object can hold.

Also read – treemap in java

Load factor/ fill ratio: is a measure to calculate after how much load a new hashset object is created.

hashset in java

NOTE: best load factor would be 0.75 with respect to time and space complexity, according to java.


HashSet hierarchy

hashset in 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.


Also read – treeset in java


Hashset 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).

Constructors in hashset

HashSet h = new HashSet();

This constructor creates an empty hashset object with default initial capacity 16 and default fill ratio or load factor 0.75

HashSet h = new HashSet(int initialCapacity);

this constructor creates hashset object with specified initialCapacity with load factor 0.75. Nothing but customized initial capacity and default load factor.

HashSet h = new HashSet(int initialCapacity, float loadFactor);

Here we can customize load factor.

HashSet h = new HashSet(Collection C);

If you want Interconversion between Collection object then use this constructor.


Let’s see an example on hashset to remove elements in different ways.

HashSet remove(Object O) method in java – this method removes the specified element from this set if it is present.

import java.util.HashSet;
public class HashSetRemoveExample
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Hi");
      hs.add("how");
      hs.add("are");
      hs.add("you");
      hs.add("doing");
      System.out.println("HashSet before using remove(Object O) method: " + hs);
      // remove elements using remove() method
      hs.remove("how");
      hs.remove("are");
      hs.remove("doing");
      // print HashSet after removal
      System.out.println("HashSet after using remove(Object O) method: " + hs);
   }
}


Output:

HashSet before using remove(Object O) method: [Hi, how, doing, are, you]
HashSet after using remove(Object O) method: [Hi, you]


Java HashSet addAll() method example – this method adds all of the elements in the specified collection to this collection.

import java.util.HashSet;
public class HashSetAddAllExample
{
   public static void main(String[] args)
   {
      HashSet<Integer> hs1 = new HashSet<Integer>();
      hs1.add(2);
      hs1.add(4);
      hs1.add(6);
      hs1.add(8);
      System.out.println("HashSet hs1: " + hs1);
      HashSet<Integer> hs2 = new HashSet<Integer>();
      hs2.addAll(hs1);
      System.out.println("HashSet hs2: " + hs2);
   }
}


Output:

HashSet hs1: [2, 4, 6, 8]
HashSet hs2: [2, 4, 6, 8]


HashSet removeAll() method in java example – this method removes from this set all of its elements that are contained in the specified collection.

import java.util.HashSet;
public class HashSetRemoveAllExample
{
   public static void main(String[] args)
   {
      try
      {
         HashSet<Integer> hs1 = new HashSet<Integer>();
         hs1.add(2);
         hs1.add(4);
         hs1.add(6);
         hs1.add(8);
         hs1.add(10);
         System.out.println("HashSet before using removeAll() method: " + hs1);
         // create another HashSet
         HashSet<Integer> hs2 = new HashSet<Integer>();
         hs2.add(2);
         hs2.add(4);
         hs2.add(6);
         System.out.println("Elements to be removed: " + hs2);
         // remove elements from hs1 described in hs2 using removeAll() method
         hs1.removeAll(hs2);
         System.out.println("HashSet after using removeAll() method: " + hs1);
      }
      catch(NullPointerException ex)
      {
         System.out.println("Exception: " + ex);
      }
   }
}


Output:

HashSet before using removeAll() method: [2, 4, 6, 8, 10]
Elements to be removed: [2, 4, 6]
HashSet after using removeAll() method: [8, 10]


java hashset removeif() method example – this method removes all of the elements of this collection that satisfy the given predicate.

import java.util.HashSet;
public class HashSetRemoveIfExample
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Banana");
      hs.add("Orange");
      hs.add("Apple");
      hs.add("Pineapple");
      hs.add("Mango");
      System.out.println("Before calling removeIf() method: " + hs);
      hs.removeIf(str -> str.contains("Orange"));
      System.out.println("After calling removeIf() method: " + hs);
   }
}


Output:

Before calling removeIf() method: [Apple, Mango, Pineapple, Orange, Banana]
After calling removeIf() method: [Apple, Mango, Pineapple, Banana]


java hashset clear() method example – this method removes all of the elements from this set. The set will be empty after this call returns.

import java.util.HashSet;
public class HashSetClearExample
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("hi");
      hs.add("how");
      hs.add("are");
      hs.add("you");
      hs.add("doing");
      System.out.println("HashSet before using clear() method: " + hs);
      hs.clear();
      System.out.println("HashSet after using clear() method: " + hs);
   }
}


Output:

HashSet before using clear() method: [hi, how, doing, are, you]
HashSet after using clear() method: []


linkedhashset in java

Linkedhashset was introduced in java 1.4 version. Underlying data structure for linkedhashset is combination of hashtable and linked list.

Insertion order in linkedhashset is preserved and will not allow duplicate elements.

Syntax:

LinkedHashSet<String> lhs = new LinkedHashSet<String>();

Linkedhashset in java constructors

  • LinkedHashSet(): this constructor constructs a new, empty linked hash set with the default initial capacity (16) and load factor (0.75).
  • LinkedHashSet(Collection<? extends E> c): this constructor constructs a new linked hash set with the same elements as the specified collection.
  • LinkedHashSet(int initialCapacity): this constructor constructs a new, empty linked hash set with the specified initial capacity and the default load factor (0.75).
  • LinkedHashSet(int initialCapacity, float loadFactor): this constructor constructs a new, empty linked hash set with the specified initial capacity and load factor.

Let’s see java LinkedHashSet example.

import java.util.LinkedHashSet;
public class LinkedHashsetExample 
{
   public static void main(String[] args) 
   {
      LinkedHashSet<String> lhs = new LinkedHashSet<String>();
      // add elements to LinkedHashSet
      lhs.add("Anteater");
      lhs.add("Bear");   
      lhs.add("Cheetah");   
      lhs.add("Deer");
      // will not add new element as Anteater already exists  
      lhs.add("Anteater");  
      lhs.add("Elephant");
      System.out.println("LinkedHashSet size: " + lhs.size());   
      System.out.println("Given LinkedHashSet: " + lhs);   
      System.out.println("Deer removed from LinkedHashSet: " + lhs.remove("Deer"));   
      System.out.println("Remove Zebra which is not present: " + lhs.remove("Zebra"));   
      System.out.println("Check if Anteater is present: " + lhs.contains("Anteater")); 
      System.out.println("New LinkedHashSet: " + lhs);
   }
}


Output:

LinkedHashSet size: 5
Given LinkedHashSet: [Anteater, Bear, Cheetah, Deer, Elephant]
Deer removed from LinkedHashSet: true
Remove Zebra which is not present: false
Check if Anteater is present: true
New LinkedHashSet: [Anteater, Bear, Cheetah, Elephant]


iterate hashset in java

To iterate hashset in java we have to use iterator() method, for-each loop and forEach() method (hashset java 8 method).

Because hashset class does not provide get() method fetch elements.

using iterator() method: this method returns an iterator over the elements in this set. The elements are returned in no particular order. Let’s see an example.

import java.util.HashSet;
import java.util.Iterator;
public class HashSetIteratorDemo 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      // add elements using add() method
      hs.add("Hello");
      hs.add("world"); 
      hs.add("Java");
      // Iterating over hashset 
      Iterator<String> iterate = hs.iterator(); 
      while(iterate.hasNext())
      {
         System.out.println(iterate.next());
      }
   }
}


Output:

Java
world
Hello


using enhanced for loop or for-each loop:

import java.util.HashSet;
public class HashSetForEach 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Hello"); 
      hs.add("world"); 
      hs.add("Java"); 
      for(String str : hs)
      {
         System.out.println(str);
      }
   }
}


Output:

Java
world
Hello


java hashset vs hashmap

Let’s learn hashset vs hashmap.

HashSetHashMap
We can store objects in HashSet. For example HashSet:{“Hello”, “World”}In HashMap we can store key and value pairs. For example {1 ->”Hello”, 2 ->”World”}
insertion order is not preserved. It is based on hashcode.does not maintain insertion order. It is based on Hash function.
has add() method.has put() method.
implements Set interface.implements Map interface.
do not allow duplicate elements.allows duplicate values. Does not allow duplicate keys.
allows single null value.allows single null key and any number of null values.

java hashmap example

import java.util.HashMap;
public class HashMapExample 
{
   public static void main(String[] args) 
   {
      HashMap<Integer, String> hm = new HashMap<Integer, String>();
      // add elements
      hm.put(10,"Apple");
      hm.put(20,"Banana");
      hm.put(30,"Cherry");
      hm.put(40,"Dragonfruit");
      // print HashMap elements
      System.out.println("HashMap elements: " + hm);
   }
}


Output:

HashMap elements: {20=BB, 40=DD, 10=AA, 30=CC}


java hashset example

import java.util.HashSet;
public class HashSetExample 
{
   public static void main(String[] args) 
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Anteater");
      hs.add("Bear");
      hs.add("Cheetah");
      hs.add("Deer");
      System.out.println("HashSet elements: ");
      for(String str : hs)
      {
         System.out.println(str);
      }
   }
}


Output:

HashSet elements:
Anteater
Bear
Cheetah
Deer


hashset contains java

HashSet contains() method in java returns true if this set contains the specified element.

Let’s see java hashset contains() method example.

import java.util.HashSet;
public class HashSetContains
{
   public static void main(String[] args)
   {
      HashSet<String> hs = new HashSet<String>();
      hs.add("Hello");
      hs.add("World");
      hs.add("Core");
      hs.add("Java");
      hs.add("Hello");
      // printing HashSet
      System.out.println("HashSet: " + hs);
      // check for "Hello" in the set
      System.out.println("Does the Set contains 'Hello'? " + hs.contains("Hello"));
      // check for "Java" in the set
      System.out.println("Does the Set contains 'Java'? " + hs.contains("Java"));
      // check if Set contains "fruit"
      System.out.println("Does the Set contains 'fruit'? " + hs.contains("fruit"));
   }
}


Output:

HashSet: [Java, Hello, World, Core]
Does the Set contains ‘Hello’? true
Does the Set contains ‘Java’? true
Does the Set contains ‘fruit’? false


Reference – docs Oracle, oracle docs