Java HashSet size() Method (original) (raw)
Last Updated : 23 Jan, 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() Method
int 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 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: