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); //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
  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
  System.out.println("Set is empty? "+set.isEmpty());

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.


Popular Posts from this Blog

Basic Structure of C++ Program - The Coding Shala

Richest Customer Wealth LeetCode Solution - The Coding Shala

Shell Script to find sum, product and average of given numbers - The Coding Shala

Shell Script to Create a Simple Calculator - The Coding Shala

First Unique Character in a String Java - The Coding Shala