Last Updated : 11 Jul, 2025
The HashSet size() method in Java is used to get the size of the HashSet or the number of elements present in the HashSet.
Syntax of HashSet size() Methodint size()
Return Type: This method returns an integer value that represents the number of elements currently stored in the HashSet.
Example: This example demonstrates the size of a HashSet.
Java
// Java program to demonstrates the working of size()
import java.util.HashSet;
public class Geeks {
public static void main(String[] args)
{
// Create a new HashSet
HashSet<String> hs = new HashSet<>();
// Add elements to the HashSet
hs.add("Geek1");
hs.add("Geek2");
hs.add("Geek3");
System.out.println("HashSet: " + hs);
// print the size of the HashSet
System.out.println("Size of HashSet: " + hs.size());
// Add element in the HashSet
hs.add("Geek4");
System.out.println("Updated HashSet: " + hs);
// print the size of the updated HashSet
System.out.println("Size of Updated HashSet: "
+ hs.size());
hs.remove("Geek1");
hs.remove("Geek3");
System.out.println("HashSet after removal of elements: " + hs);
// print the size of the HashSet after removal
System.out.println("Size of HashSet after removal: "
+ hs.size());
}
}
Output:
RetroSearch is an open source project built by @garambo | Open a GitHub Issue
Search and Browse the WWW like it's 1997 | Search results from DuckDuckGo
HTML:
3.2
| Encoding:
UTF-8
| Version:
0.7.4