Java HashSet Tutorial: Unique Elements, Methods & Examples

ZoneTechPro
By -
0


 HashSet


Java HashSet Tutorial: Unique Elements, Methods & Examples
Java HashSet



Introduction

Previously, we have seen in our module on Java the arrays and ArrayLists. Both Arrays and ArrayLists can contain an element greater than one.


Now in this unit, we shall see the HashSet that holds unique items.


1. HashSet

There is also Java built-in class, HashSet, much like the set in Python, which gives the functionalism of a set.


A HashSet is an unordered collection with unique elements that should not be repeated.


A HashSet class is from package java.util.


HashSet contains only objects like String, Integer, etc., just like ArrayList.


Declaration of HashSet

The declaration of HashSet works with the following syntax:


Syntax


HashSet<Type> hset = new HashSet<>();


Here,


HashSet is the class name

hset is the name of the variable

Type is the data type of the hset

Now let us create a HashSet called players, with type String.


Code


import java. util.HashSet.


class Main {

    public static void main(String[] args) {

        HashSet<String> players = new HashSet<>();

    }

}


This code shows that we have created an empty HashSet which has assigned to the players variable.



2. Add Stuff to HashSet

Add element in HashSet using the add() function which is exactly like in Python for adding a single element to the HashSet. 


If the element is not already in the collection, it is added to the collection and true is returned. Otherwise , it does not add it to the set and returns false.


HashSet behaves pretty much the same as an ArrayList in that automatically resizes whenever an element is added or removed. 


Syntax


hset.add(element);


Where,


hset is the variable name

element is the element to be added


Example 1:


Code


import java.util.HashSet;


class Main {

    public static void main(String[] args) {

        HashSet<String> players = new HashSet<>();

        players.add("Rohit");

        players.add("Virat");

        players.add("Sachin");

        System.out.println(players);

    }

}


Output:


[Rohit, Virat, Sachin]

It can print a HashSet similar to an ArrayList. 


Example 2: 


Code


import java.util.HashSet;


class Main {

public static void main(String[] args) {

HashSet<String> players = new HashSet<>();

boolean isAdded = players.add("Rohit");

System.out.println(isAdded);

System.out.println(players);

isAdded = players.add("Rohit");

System.out.println(isAdded);

System.out.println(players);

}

}


Output:


true

[Rohit]

false

[Rohit]


This is because initially, it treats the Hashset as empty. Hence, one call to add() added the string Rohit to the HashSet and returned true; next time, even though the string was added to HashSet at the first time, this time it returned false because already the given string in add was in collection.



3. Removing Elements from HashSet

Two methods may remove an element from HashSet:


remove()

clear()


remove()

The remove() method removes an element from the HashSet.


It removes the element and returns true if the HashSet contains the specified element, otherwise it returns false.


Syntax


hset.remove(element);


Here element is a value to be removed from the HashSet.


Code


import java.util.HashSet;


class Main {

    public static void main(String[] args) {

        HashSet<String> players = new HashSet<>();

        players.add("Rohit");

        players.add("Virat");

        players.add("Sachin");

        System.out.println("Before Removing: " + players);

        boolean isRemoved1 = players.remove("Virat");

        boolean isRemoved2 = players.remove("Kane");

        System.out.println(isRemoved1);

        System.out.println(isRemoved2);

        System.out.println("After Removing: " + players);

    }

}


Output:


Before Removing: [Rohit, Virat, Sachin]

true

false

After Removing: [Rohit, Sachin]


In the above code, Virat is present in the players HashSet and Kane is not present. Hence, isRemoved1 contains true, isRemoved2 contains false, and Virat is removed from the HashSet.


clear()

The clear() method removes all the elements from a HashSet.


It only removes the elements from the HashSet and does not delete the HashSet.


Syntax


hset.clear();


Code:


import java.util.HashSet;


class Main {

    public static void main(String[] args) {

        HashSet<String> players = new HashSet<>();

        players.add("Rohit");

        players.add("Virat");

        players.add("Sachin");

        System.out.println("Before Clearing: " + players);

        players.clear();

        System.out.println("After Clearing: " + players);

    }

}


Output:


Before Clearing: [Rohit, Virat, Sachin]

After Clearing: []



4. Searching in a HashSet.

The contains() method checks whether some element is a part of the given HashSet. If the element is found, then it returns true; otherwise, false is returned.


Syntax


hset.contains(element);


Here, element is a value to be searched in HashSet.


Code


import java.util.HashSet;


class Main {

    public static void main(String[] args) {

        HashSet<String> players = new HashSet<>();

        players.add("Rohit");

        players.add("Virat");

        players.add("Sachin");

        boolean isPresent1 = players.contains("Virat");

        boolean isPresent2 = players.contains("Kane");

        System.out.println(isPresent1);

        System.out.println(isPresent2);

    }

}


Output:

true 

false


5. Size of HashSet

The method size() is used to find the size of a HashSet.


Syntax

hset.size();


import java.util.HashSet;


class Main {

public static void main(String[] args) {

HashSet<String> players = new HashSet<>();

players.add("Rohit");

players.add("Virat");

players.add("Sachin");

System.out.println(players);

System.out.println(players.size());


}

}


Output:

[Rohit, Virat, Sachin]

3


6. Iterating Through a HashSet

You can also iterate through a HashSet by using the for-each loop, just like iterating through an Array or ArrayList.


Code


import java.util.HashSet;


class Main {

public static void main(String[] args) {

HashSet<String> players = new HashSet<>();

players.add("Rahul");

players.add("Rohit");

players.add("Virat");

players.add("Sachin");

for (String name : players) {

System.out.println(name);

}

}

}


Output:


Rohit

Rahul

Virat

Sachin



Summary

HashSet is an unordered collection of elements. HashSet elements are unique.


HashSet Methods:


add(): adds a single element to a HashSet.


remove(): removes an element from a given HashSet. It returns true if a HashSet contains the specified element, otherwise false.


clear(): removes all the elements from a HashSet.


contains(element): checks if an element is present in a given HashSet. It returns true if the element is found, otherwise false.


size(): finds the size of a HashSet.


The for-each loop can be used to iterate over a HashSet.

Tags:

Post a Comment

0Comments

Post a Comment (0)

#buttons=(Ok, Go it!) #days=(20)

Our website uses cookies to enhance your experience. Learn more
Ok, Go it!