Java HashSet - The Coding Shala

Home >> Learn Java >> HashSet

Java HashSet

In this post, we will see what is Java HashSet and its implementation with example.

Java HashSet is one of the implementations of a set. The HashSet is a data structure to store no repeated values. That means all the values are unique in HashSet. 

Java HashSet Implementation

The following Java program explains the basic implementation of Java HashSet: 

import java.util.HashSet;

//HashSet Example 

class Main{
 public static void main(String[] args) {
  //initialize hashset
  HashSet<Integer> set = new HashSet<Integer>();
  
  //add value to 
  //use add(value) method
  set.add(1);
  set.add(2);
  set.add(3);
  set.add(4);
  set.add(1); //duplicate
  System.out.println("Set is: "+set);
  
  //check if value is present or not
  System.out.println("Value 4 is present in set? "+set.contains(4));
  
  //remove value
  //use remove(object) method
  set.remove(4);
  System.out.println("Set is: "+set);
  
  //size() size of set
  System.out.println("Size of set is: "+set.size());
  
  //check empty or not
  //use isEmpty() method
  System.out.println("Set is empty? "+set.isEmpty());
  
  //clear hashset
  //use clear() method
  set.clear();
  System.out.println("Set is empty? "+set.isEmpty());
 }
}
Output: 

Set is: [1, 2, 3, 4]
Value 4 is present in set? true
Set is: [1, 2, 3]
Size of set is: 3
Set is empty? false
Set is empty? true


Other Posts You May Like
Please leave a comment below if you like this post or found some error, it will help me to improve my content.

Comments

Popular Posts from this Blog

Shell Script to Create a Simple Calculator - The Coding Shala

N-th Tribonacci Number Solution - The Coding Shala

Java Program to Convert Binary to Decimal - The Coding Shala

LeetCode - Shuffle the Array Solution - The Coding Shala

Java Program to Find GCD or HCF of Two Numbers - The Coding Shala