Different HashSet() methods in Java

Set is an unordered collection of values in which duplicate values are not allowed. Set can be implemented using HashSet. In this Java tutorial, we are going to discuss different HashSet() methods in Java.

You can also learn,

Different HashSet() methods in Java

Now, we will learn each HashSet methods in Java with some easy examples and explanations.

HashSet add() Method in Java

The Java.util.HashSet.add() method in Java HashSet is used to add a particular element into a HashSet. This method will add the element if a particular element is not present in HashSet.

            Syntax :- Hash_Set.add(value)

The value passed as a parameter will be added in HashSet.

HashSet contains() Method in Java

To check if a particular element is present in HashSet or not we can use the Java.util.HashSet.contains() method. This method will return true if a particular element is present in HashSet.

Syntax :- Hash_Set.contains(value)

The parameter passed is value to checked if it is in Hashset or not.

HashSet remove() Method in Java

The Java.util.HashSet.remove(value) method is used to remove the specified element from HashSet.

           Syntax :- Hash_Set.remove(value)

The parameter passed is value to be removed from HashSet.

HashSet isEmpty() Method in Java

Finally, To check if a HashSet is empty or not we can use The Java.util.HashSet.isEmpty() Method.

   Syntax :- Hash_Set.isEmpty()

Java Code for Different HashSet() Methods in Java

import java.io.*;

import java.util.HashSet;

   public class Codespeedy

      public static void main( String[] args)
        HashSet<String> s = new HashSet<String>();
           System.out.println("Does HashSet contains 'Code'? :- "+s.contains("Code"));
            System.out.println("Is HashSet empty :- "+s.isEmpty());


HashSet:-[Speedy, Code]
Does HashSet contains 'Code' :- ?true
Is HashSet empty :- true

You can also learn,

Leave a Reply

Your email address will not be published. Required fields are marked *