×

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

Java Xmx

This section will explain what Xmx in Java is and how to establish a Java application's maximum heap size. When we execute a Java application, it occasionally displays an error message...

3 minutes read.

Morris Traversal for Inorder in Java

Through Morris’s traversal, a tree is traversed without the aid of recursion or stacks. Based on the threaded binary tree, the Morris traversal is used. We perform internal modification throughout...

4 minutes read.

Java String replace() method

Java String replace() method returns new String by replacing old characters with new characters or old CharSequence to new CharSequence. Syntax: public String replace(char oldChar, char newChar) public String replace(CharSequence target, CharSequence replacement) Parameters: oldChar...

2 minutes read.

Java Package Keyword

A collection of classes, interfaces, and subpackages in a Java program are referred to as a package. Here, we'll learn in-depth how to make and use user-defined packages. package is a...

6 minutes read.

Constructor Program in Java

Constructor Program in Java In Java, a constructor is a piece of code that is used to create an object. A constructor is called implicitly when an object is created in...

7 minutes read.

Thread Concept in Java

What is a Thread? A subprocess that is lightweight in Java is known as a thread. It is the smallest unit of a process. For the running of multiple tasks parallelly...

3 minutes read.

How to Set Java_home in Linux

To set the Java_home in Linux, we must follow several steps to make us understand it easily.  Java follows the principle called WORA (write once run anywhere). We know that java...

3 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.

India Map Pattern in Java

India Map Pattern is the pattern we'll code now using Java, as demonstrated. We will use a star in Java to print our India map.The specialty is that we will only...

4 minutes read.

Java Integer max() method

The max() method of Integer class returns the greater of two int values. It returns the same result as by calling Math.max. Syntax public static int max(int a, int b) Parameters The parameters ‘a’...

2 minutes read.

How to add 4 Years to the Current Date in Java?

In this tutorial, we will learn how to add 4 years to the local or current date in Java language. We will begin our topic with basic concepts and would...

2 minutes read.

CopyOnWriteArrayList in Java

The CopyOnWriteArrayList is used to implement the List Interface. It is the improved version of ArrayList. The operations like add, remove, set, update etc, these operations are done by creating...

5 minutes read.

Producer consumer problem in Java using Synchronised block

The producer-consumer problem in Java, commonly known as the bounded-buffer problem, is a well-known multi-process synchronization challenge where we attempt to synchronize many processes. Two processes are involved in the producer-consumer problem:...

3 minutes read.

Magic Square in Java

A square with numbers is referred to as a magic square. The numbers in a magic square of order n are arranged to ensure that the sum of all of...

4 minutes read.

Skyline Problem in Java

The skyline of a city is the outer edge of the pattern created by all of its structures when viewed from a distance. Return the skyline that these buildings together...

4 minutes read.

Java Naming Conventions

JAVA NAMING CONVENTIONS Java naming convention is a standard pattern for writing your identifier name such as class, interfaces, methods, constants, variable, etc. These patterns are not standard rules that you must...

2 minutes read.

Libraries in Java

The Java Class Library (JCL) specifically is a set of dynamically loadable libraries that Java Virtual Machine (JVM) languages can call at any run time, which is fairly significant because...

6 minutes read.

Java String Concatenation

Java String Concatenation Java programming provide a way to combine multiple strings into a single string. It is called as String Concatenation. There are different ways to concatenate two or more...

4 minutes read.

Java Integer equals() method

The equals() method of Integer class compares the given object to the specified object. Syntax public boolean equals(Object obj) Parameters The parameter ‘obj’ represents the object to be compared with. Overrides The equals() method overrides equals...

1 minute read.

Hamming Code in Java

In a computer network, hamming code is a unique set of error-correction codes. It is mostly utilised in computer graphics for mistake detection and correction during data transmission from sender...

8 minutes read.