×

Various operations on HashSet in Java

In this article, you will be acknowledged about what is a HashSet in java and what are its operations in java programming language. The HashSet is a crucial part of collection framework.

HashSet in Java

A hash table that is basically a HashMap instance serves as the foundation for the HashSet class, which implements the Set interface. The set's iteration order is not guaranteed; hence the class doesn't really assure that the components will remain in the same order throughout time. The null element is permitted by this class. Additionally, the class provides constant-time performance for operations like as add, delete, contains, and size under the condition that the elements are distributed evenly across the buckets by the hash function. HashSet uses the hashing technique to store the components.

HashSet has quite a several key characteristics, including:

  • Carries out Set Interface.
  • HashTable is the basic data structure for HashSet.
  • Repeated values are not permitted because it supports the Set Interface.
  • The sequence in which items are added into a hash set is not always guaranteed to be the same. Depending on their hash code, objects are added.
  • In a hash set, NULL elements are permitted.
  • Additionally, HashSet supports the Serializable and replicate interfaces.

Different Operations on a HashSet

Appending Elements

The add() method is available for adding new elements to the HashSet. But the HashSet does not keep track of the insertion order. It's important to remember that all duplicate items are ignored and that they are not permitted.

Let us go through a small example program to understand.

File name: Append.java

// Programming in Java to Add Elements to HashSet
//loading the necessary classes
import java.io.*;
import java.util.*;
class Append {


public static void main(String[] args)
{ 
// building a blank string entity hash set
HashSet<String> h = new HashSet<String>();


// leveraging the add() method to add components
h.add("I");
h.add("am");
                          h.add("Robin");
h.add("Hood");
// displaying each string entry in the Set
System.out.println("HashSet elements are: " + h);
}
}

Output

HashSet elements are: [I, am, Robin, Hood]

Eliminating Elements

The remove() method can be used to eliminate the values from the HashSet.

Let us go through a small example program to understand.

File name: Eliminate.java

// Java Program Demonstrating the Removal of HashSet Elements and the Importation of //Necessary Classes
import java.io.*;
import java.util.*;


class Eliminate {


public static void main(String[] args)
{

HashSet<String> h = new HashSet<String>();
                           // adding components to the above-mentioned set
// using the function add()
h.add("I");
h.add("am");
h.add("Robin");
h.add("Hood");
h.add("from");
h.add("Canada");


// printing the components of a hash set
System.out.println("Initial HashSet " + h);


// Eliminating an item 
h.remove("I");


// displaying the modified HashSet components
System.out.println("After removing element " + h);


// If a element is absent, the return value is false.
System.out.println("Element ON exists in the Set : "
+ h.remove("on"));
}
}

Output

Initial HashSet [I, am, Robin, Hood, from, Canada]
After removing element [ am, Robin, Hood, from, Canada]
Element ON exists in the Set : false

Going through the HashSet repeatedly

Utilize the iterator() method to cycle over the HashSet's elements. The most well-known method also involves using the improved for loop.

Let us go through a small example program to understand.

File name: Iteration.java

// Java Program to Demonstrate HashSet Iteration Importing Necessary Classes
import java.io.*;
import java.util.*;
class  Iteration{
public static void main(String[] args)
{
// making a string HashSet with no entries
HashSet<String> h = new HashSet<String>();


// adding components to the above-mentioned set
// using the function add()
h.add("I");
h.add("am");
h.add("Robin");
h.add("Hood");
h.add("from");
h.add("Canada");


// use iterators to iterate across the HashSet
Iterator itr = h.iterator();


// until there is only one element left in the set, true
while (itr.hasNext())


// elements that have been traversed and printed
System.out.print(itr.next() + ", ");
System.out.println();


// traversal using improved for loop
for (String s : h)


// elements that have been traversed and printed
System.out.print(s + ", ");
System.out.println();
}
}

Output

[I, am, Robin, Hood, from, Canada]
[I, am, Robin, Hood, from, Canada]

Hashtable is the base data structure for HashSet. Therefore, the add, remove, and take a simply look (includes method) operations of the HashSet amortise (average or normal case) time complexity in O(1) time.


Related Topics

Switch Case Program in Java

Switch Case Program in Java The switch case program in Java controls which code snippet gets executed on the basis of the value of the expression mentioned in the switch statement....

22 minutes read.

Zigzag Traversal of Binary Tree in Java

In this article, you will be acknowledged about the zigzag traversal of binary tree in java and the approaches or ways in which the zigzag traversal can be done. Zigzag Traversal A...

10 minutes read.

String Pool in Java

String Pool in Java: String is one of the most important discussed topics in Java. There are a lot of concepts related to the String and one of them is...

5 minutes read.

public static void main string args meaning in java

In java main() method is the initial point for execution of the program. If a program doesn’t contain the main method, the program will not execute. JVM(java virtual machine) starts...

3 minutes read.

Model Class in Java

In this section, we will be acknowledged about the model class in Java, its purpose and its uses. Also, we will learn how is this created and leveraged in java. Model...

4 minutes read.

Creating a Custom Generic Class in Java

To indicate parameter types when creating generic classes, we utilize the <> symbol. The syntax used to generate objects of a generic class is as follows. // To create an instance...

4 minutes read.

Java Boolean Class

The Boolean class wraps a value of the Boolean primitive in an object. Its object contains only a single field whose type is Boolean. Boolean Methods: This class contains several different methods...

2 minutes read.

How to Reverse a String in Java

How to Reverse a String in Java There are a lot of ways to reverse a string in Java. One can use iteration, StringBuilder, StringBuffer to do the reverse of a...

6 minutes read.

Literals in Java

In this article we acknowledge ourselves about the term literals in java, types of literals and an example to each of them. Literal Literal refers to any constant value that can be...

4 minutes read.

Java concurrency interview questions

During technical interviews, one of the most challenging and sophisticated subjects is concurrency in Java. This page offers responses to some of the related interview questions you might come across. 1....

11 minutes read.

Java Maven Silicon

Maven is a build automation tool that is mostly used for Java applications. It allows you to manage the build, reporting, and documentation of a project from the central location. Maven provides...

4 minutes read.

Getting the Day from the Date in Java?

To extract the day's name from the date, we will write Java application. When dealing the date and time in Java, the following classes are used. Class for Calendars: This class is...

6 minutes read.

How to Calculate the Time Difference between Two Dates in Java?

The date is used extensively in Java to calculate date discrepancies. The date of joining an organization, admittance, appointment, etc., can be included when creating the application. The differences between...

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

Java throw

Java throw Sometimes it is required in the code to throw an exception deliberately. In order to achieve the same, the Java throw keyword should be used. One can throw either...

3 minutes read.

Java Extends keyword

Extends Extends is a keyword which is completely depended on the concept of the inheritance of the java programming language.To understand about of the keyword, we need to learn the concept...

3 minutes read.

How to calculate time complexity of any program in Java

Java : Java's syntax and principles are derived from the C and C++ languages. We know that java is one of the programming language. The main feature of java which is...

3 minutes read.

Nonagonal number in Java

Figureate numbers with the form n(7n-5)/2 are known as nonagonal numbers. 7n+3 will be a triangular number if n is a nonagonal number. The nonagon is included in the idea...

4 minutes read.

Iccanobif Numbers in Java

In this article, you will be very well equipped with the knowledge of iccanobif numbers in Java. You will also know how they are formed and basic example programs on...

3 minutes read.

Date time API in java

Introduction: In this text, we can talk approximately Data time API in java. The java.time, java.util, java.sql, and java.text packages contain classes that represent dates and times. The following classes are...

4 minutes read.