×

Java HashSet

HashSet implements the set interface. It uses the hash table to make the collection to store different data types. The hash set is the unordered collection of different data types. In other words, we can say that the hash set doesn't maintain the order of insertion of the elements. The HashSet contains unique elements only. The duplicate elements inserted into the HashSet are considered only once in the collection. It can also contain null values. The indexing in the HashSet is done according to the Hash value of the element inserted into the HashSet. The default value of the initial position is 16, and the load factor is 0.75. Load factor and initial capacity are two factors which affect the performance of the Hash Table. Initial Capacity: It is the number of buckets in the Hash table. If the current size is full, then the number of buckets is automatically increasing. Load Factor: It decides when it increases the capacity of the Hash Map. Load Factor= Number of stored elements in the table/ Size of Hash Table. Time Complexity of Hash Set: HashSet uses the data structure is HashTable. The Average time complexity of HashSet for add(), remove(), contains() methods operation is O(1) time.

Internal working of HashSet:

The classes of the set interface are internally back up by Map. HashMap used to store the object internally in HashSet. When we enter the value in HashMap, then we need a key-value pair, but in HashSet, we need only value. Implementation:
public transient HashMap map;
public HashSet()
{
map=new HashMap (); // creating internally backing HashMap object.
}
public HashSet (int initialCapacity)
{
map= new HashMap (initialCapacity); // creating internally backing HashMap object.
}
private static final object PRESENT= new Object (); //Dummy value
public boolean add (E e)
{
return map.put (e, PRESENT) ==null; //internally calls put () method of backing HashMap object to passing the elements.
}
public boolean remove (object o)
{
return map.put (o) == PRESENT; //internally call remove method of Map interface.
}

Constructor

  1. HashSet (): It constructs the default HashSet.
  2. HashSet (Collection c): It initializes the HashSet using the elements of the collection.
  3. HashSet (int capacity): This initializes the capacity of the HashSet. The capacity of HashSet increased automatically when elements added in Hash set.
  4. HashSet (int capacity, float Loadfactor): This initializes the capacity of the HashSet and the load factor of the HashSet from its parameters. The load factor enters in float type and capacity at the given integer value type.

Methods

  1. add (Element e): It is used to add the specific element. If the element is present then returns false.
  2. clear (): It is used to remove all the elements of the set.
  3. contains (object o): It returns true when the elements found in the set.
  4. remove (object o): It is used to delete the element if element present in the set.
  5. iterator (): It is used to return the iterator in the set.
  6. isEmpty (): This method is used to check the set is empty or not.
  7. int size (): This method is used to return the size of the set.
  8. Object clone (): This method is used to create the same copy of the set.
    Traversing
  • Using iterator: The iterator () method is to get an iterator over the element in the set. There is no particular order for returning the element.
Example:
import java.util.*;
public class IterationDemo {
public static void main (String[] args)
{
 HashSet<String> h = new HashSet<String> ();
h.add ("TutorialAndExample");
h.add ("for");
h.add ("Study purpose");
h.add ("Study purpose");
Iterator<String> i = h.iterator ();
while (i.hasNext ())
System.out.println (i.next ());
    }
}
Output:
TutorialAndExample
for
Study purpose
  • Using for-each loop:
Example:
import java.util.*;
public class IterationDemo {
public static void main (String [] args)
{
 HashSet<String> h = new HashSet<String> ();
h.add ("TutorialAndExample");
h.add ("for");
h.add ("Study purpose");
h.add ("Study purpose");
for (String i: h) 
System.out.println (i);
    }
}
Output:
javatpoint
for
Study purpose
  • Using forEach ():
Example:
import java.util.*;
public class IterationDemo {
public static void main (String [] args){
HashSet<String> h = new HashSet<String> ();
h.add ("TutorialAndExample");
h.add ("TutorialAndExample");
h.add ("for");
h.add ("Study Purpose"); 
h.forEach (i -> System.out.println (i));
    }
}
Output:
Study Purpose
for
TutorialAndExample

Difference between HashSet and TreeSet

HashSet TreeSet
1. Performance is faster. 1. Performance is slower for most of the general operation, i.e., add, remove and search.
2. There is no particular order for an element. 2. Tree set provides the order for elements.
3. For comparing, it uses the equals () method. 3. For comparing, it uses the compareTo () method.
4. The data structure for the hash set is HashTable. 4. The Data Structure for TreeSet is Red-Black Tree.
5. It allows only one null element. 5. It doesn’t allow null element.
6. Implemented using HashMap. 6. Implemented using TreeMap.
add () method:
import java.io.*;
import java.util. HashSet;
public class AddDemo {
public static void main (String args []) {
HashSet<String> set = new HashSet<String> ();
set.add ("Welcome");
set.add ("To");
set.add ("TutorialandExample");
System.out.println ("HashSet: " + set);
    }
}
Output:
HashSet: [Welcome, TutorialandExample, To]
Example of clear () method:
import java.io.*;
import java.util. HashSet;
public class ClearDemo {
public static void main (String args []) {
HashSet<String> set = new HashSet<String> ();
set.add ("Welcome");
set.add ("To");
set.add ("TutorialandExample");
System.out.println ("HashSet: " + set);
set.clear ();
System.out.println ("The final set: " + set);
    }
}
Output:
HashSet: [Welcome, TutorialandExample, To]
The final set: []

contains () method

import java.io.*;
import java.util. HashSet;
public class ContainDemo {
public static void main (String args []) {
HashSet<String> set = new HashSet<String> ();
set.add ("Welcome");
set.add ("To");
set.add ("TutorialandExample");
System.out.println ("HashSet: " + set);
 System.out.println ("Does the Set contain ‘TutorialandExample’?” + set.contains ("TutorialandExample"));
System.out.println ("Does the Set contain ‘4’?” + set.contains ("4"));
System.out.println ("Does the Set contains ‘and’?" + set.contains ("and"));
}
}
Output:
HashSet: [TutorialandExample, Welcome, To]
Does the Set contain 'TutorialandExample’? true
Does the Set contain '4'? false
Does the Set contains 'and'? false
remove () method
import java.io.*;
import java.util. HashSet;
public class ContainDemo {
public static void main (String args []) {
HashSet<String> set = new HashSet<String> ();
set.add ("Welcome");
set.add ("To");
set.add ("TutorialandExample");
System.out.println ("HashSet: " + set);
set.remove ("Welcome");
System.out.println ("HashSet after remove the elements: "+ set);
}
}
Output:
HashSet: [TutorialandExample, Welcome, To]
HashSet after remove the elements: [TutorialandExample, To]
isEmpty () method:
import java.io.*;
import java.util. HashSet;
public class EmptyDemo {
public static void main (String args []) {
HashSet<String> set = new HashSet<String> ();
set.add ("javatpoint");
set.add ("and");
set.add ("TutorialandExample");
System.out.println ("HashSet: " + set);
System.out.println ("Is the set empty: " + set.isEmpty ());
set.clear ();
System.out.println ("Is the set empty: " + set.isEmpty ());
}
}
Output:
HashSet: [TutorialandExample, Welcome, To]
Is the set empty: false
Is the set empty: true
size () method:
import java.io.*;
import java.util. HashSet;
public class SizeDemo {
public static void main (String args []) {
HashSet<String> set = new HashSet<String> ();
set.add ("Welcome");
set.add ("To");
set.add ("TutorialandExample");
System.out.println ("HashSet: " + set);
System.out.println ("The size of set is: " + set.size ());
}
}
Output:
HashSet: [TutorialandExample, Welcome, To]
The size of set is: 3 
clone () method:
import java.io.*;
import java.util. HashSet;
public class CloneDemo {
public static void main (String args []) {
HashSet<String> set = new HashSet<String> ();
set.add ("Welcome");
set.add ("To");
set.add ("TutorialandExample");
System.out.println ("HashSet: " + set);
HashSet clone= new HashSet ();
clone = (HashSet) set.clone ();
System.out.println ("The new set: " + clone);
}
}
Output:
HashSet: [TutorialandExample, Welcome, To]
The new set: [Welcome, To, TutorialandExample]
iterator () method:
import java.io.*;
import java.util.*;
public class IteratorDemo {
public static void main (String args []) {
HashSet<String> set = new HashSet<String> ();
set.add ("Welcome");
set.add ("To");
set.add ("TutorialandExample");
System.out.println ("HashSet: " + set);
Iterator value = set.iterator (); 
System.out.println ("The iterator values are: ");
while (value.hasNext ()) {
System.out.println (value.next ());
}
}
}
Output:
HashSet: [TutorialandExample, Welcome, To]
The iterator values are:
TutorialandExample
Welcome
To

Related Topics

Palindrome Partitioning problem in Java

In this article, you will be acknowledged about partitioning of the palindrome. It can be done in many ways. This article makes sure every method is discussed. Palindrome If a string remains...

6 minutes read.

Java TreeMap

TreeMap in Java with Example Java TreeMap implements the NavigableMap interface. It extends Map Interface. Java TreeMap is based on the red-black Tree implementation. It stores the key-value pair in sorted...

7 minutes read.

Nested Enum in Java

A class that can be defined within another class is called a nested class in Java. You can logically group classes that are used onlyin one place. This makes encapsulation...

3 minutes read.

Sorting Program in Java

Sorting Program in Java: The sorting program in Java is used to sort arrays either in ascending or descending order.  There are two predefined methods available in Java that are...

6 minutes read.

Tug of War in Java

As in the tug-of-war issue, we must divide the given collection of n numbers into two groups of sizes that are equal or nearly equivalent. A minimum difference must exist...

5 minutes read.

Java Program to print even and odd numbers using 2 threads

Using two threads in a single thread is even odd printing in Java programming with multiple threads. To create code that prints even and odd using two threads, we must...

2 minutes read.

Java Get Time in UTC

UTC is the abbreviation for Universal Time Coordinated. Before the beginning of UTC, it is mentioned as the Greenwich Mean Time (GMT) but Now it is mentioned as the universal...

4 minutes read.

How to Convert Timestamp to Date in Java

How to Convert Timestamp to Date in Java You can convert Timestamp to Date by using the constructor of Date class. It returns the long millisecond from Epoch (1st January 1970)...

2 minutes read.

Synchronized Keyword in Java

Synchronization is the process of limiting access to a shared resource or data to a single thread at a given moment in time. This aids in shielding the data from...

6 minutes read.

Untouchable Number in Java

If a number N cannot be divided properly by any positive number, it is said to be an untouchable number. Additionally known as nonaliquot numbers. The sequence is A005114 from...

3 minutes read.

Comparator vs Comparable in Java

Comparator Vs Comparable in Java In Java, sorting of primitive data types can be done using different inbuilt functions that are available. But for sorting the collection of objects or types...

4 minutes read.

What is anagram in Java?

In this section will explain what an anagram is in Java and demonstrate how to determine whether or not a text is an anagram. In Java interviews, the anagram Java...

4 minutes read.

How Many Ways to Create Objects in Java

Introduction Java comes under the category of object-oriented programming languages. Since it is object-oriented, everything in Java is considered an object. Java is a diverse programming language that is designed to...

6 minutes read.

URLConnection class in Java

A communication channel between the URL and the program is represented by the Java URLConnection class. It may be utilized to read from and write to the given resource the...

4 minutes read.

Swastika Pattern in Java

This part teaches us how to create the Swastika Pattern in Java utilizing user-defined columns and rows as well as stars or other special characters.A Java pattern application that is...

2 minutes read.

Enum Java Interview Questions

1. What exactly is Java? Java is a portable, high-level, object-oriented, robust, secure, platform-independent, multi-threaded, high-performance programming language. Developed in June 1991 by James Gosling, also known as Platform. 2. Enum is...

3 minutes read.

Java Extends vs Implements

Java: We known that the java is a pure object oriented programming language. Java programming language consists of many features such as portable, plat form independence, secured, robust, simple, architecture neutral,...

4 minutes read.

What is new in Java 17?

Java 17 LTS is the most recent long-term support release for the Java SE platform. Under the Oracle No-Fee Terms and Conditions License, which stands for long-term support, JDK 17...

6 minutes read.

Java Math toRadians() Method

The toRadians() method of Java Math class converts an angle measured in degrees to an approximately equivalent angle measured in radian. Syntax: public static double toRadians (double angdeg) Parameters The parameter ‘angdeg’ represents an...

2 minutes read.

Figurate Number in Java

There have been several uses for figurate or figural numerals throughout history. A number that may be expressed by regular, distinct geometric shapes with spaced evenly points is referred to...

4 minutes read.