×

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

Blockchain in Java

Blockchain is a continuously expanding ledger that maintains an immutable, secure, and chronological record of all transactions that have ever occurred. It can be utilized to securely transfer money, assets,...

9 minutes read.

Multithreading in Java

Multithreading is a specialized form of multitasking. It is responsible for executing more than one task at a time of a single program, and each task is a separate thread. A program...

8 minutes read.

Java 8 filters list

A stream with the components of this stream that match the given predicate is provided by the streaming filter (Predicate predicate). This process is step-by-step. Because these operations are always...

4 minutes read.

Java Set to List

In this article, you will be acknowledged about how the process of conversion from Set or HashSet to LinkedList happens and what are the possible ways involved in conversion process. First...

4 minutes read.

Narcissistic Number in Java

A Narcissistic number is made up of digits that have been added together and raised to powers equal to the number of digits in the original number. In those other...

3 minutes read.

Java Math sinh() Method

The sinh() method of Java Math class returns the hyperbolic sine of the specified double value. Syntax: public static double sinh(double x) Parameters: The parameter ‘a’ represents the number whose hyperbolic sine is to...

2 minutes read.

Interchange Diagonal elements in Java

In this article, you will be very well acknowledged about what is a matrix with an example. You will also be acknowledged about how to interchange the diagonal elements in...

4 minutes read.

Flag Pattern in Java

The flag pattern in Java can be printed, which will be covered in this part. Given how difficult they are to code, flag patterns are rarely asked by interviewers. We separate...

2 minutes read.

Memory Leak in Java

Java offers memory management right out of the box. When we use the new keyword to create an object, the JVM initialises for that object immediately. The trash collector automatically...

3 minutes read.

Misc Operators in Java

In this article, we are going to learn about the misc operators in Java. Misc operators are nothing but the miscellaneous operators. The java programming language supports some of the...

4 minutes read.

Java Integer decode() method

The decode() method of Integer class decodes a String into an Integer. It can accept decimal, hexadecimal and octal numbers. Syntax public static Integer decode(String nm) throws NumberFormatException Parameters The parameter ‘nm’ represents the...

2 minutes read.

Java Append Data to File

When writing data to a file using the classes within the java.io package, its file will often be overwritten, meaning that any existing data will be removed and new data...

4 minutes read.

Minimum Lights to Activate Java Snippet Class

Minimum Lights to Activate Problem in Java In prison, there is a hallway that is N units long. Given an N-dimensional array A. If the light at the ith position is...

3 minutes read.

Logger class in Java

Logging is a crucial component of Java that aids developers in tracking down mistakes. The logging technique is included with the computer language Java. The possibility of collect the log...

7 minutes read.

Static vs Non-Static in Java

A static method can access and update the value of a static data member. The static keyword is mostly used in Java for memory management. The static keyword can be...

6 minutes read.

Tetranacci Number in Java

This article mainly describes tetranacci number identification and the Java Program for Tetranacci numbers. Tetranacci number Tetranacci numbers and Fibonacci numbers are related. The key contrast is that a Tetranacci number depends...

3 minutes read.

Get yesterdays date by no of days in Java

In this tutorial, we are going to learn how to get yesterday’s date by the no of days in Java. Using the Calendar class, one can get the current date....

1 minute read.

Java ResultSetMetaData

The data about another data is called Metadata. The ResultSetMetaData is used to store the data about ResultSet. The ResultSet Contains the columns, rows, names of table, datatypes etc. these...

2 minutes read.

Centered Square Numbers in Java

In this tutorial, we will understand how to check the number is a centered square number. It is one of the prevalent interview questions of IT companies. Firstly, we will...

3 minutes read.

Streams in Java

The conventional Java SE 8 version came with many new peculiarities, out of which the most striking of which are assuredly lambda expressions and the method references. Streams and Streams...

14 minutes read.