Java HashSet.size() – Examples

In this tutorial, we will learn about the Java HashSet.size() method, and learn how to use this method to get the size of this HashSet, with the help of examples.

size()

HashSet.size() returns the number of elements in this HashSet.

Syntax

The syntax of size() method is

</>
Copy
HashSet.size()

Returns

This method returns Integer value.

Example 1 – size()

In this example, we will define and initialize a HashSet of Strings. We shall then find the number of elements in this HashSet using size() method.

Java Program

</>
Copy
import java.util.HashSet;

public class Example {  
	public static void main(String[] args) {
		HashSet<String> hashSet = new HashSet<String>();
		hashSet.add("a");
		hashSet.add("b");
		hashSet.add("c");
		hashSet.add("d");
		
		int result = hashSet.size();
		System.out.println("Size of this HashSet is : " + result);
    }  
}

Output

Size of this HashSet is : 4

Example 2 – size() – Empty HashSet

In this example, we will define and initialize an empty HashSet of Strings. As the HashSet is empty, HashSet.size() returns 0.

Java Program

</>
Copy
import java.util.HashSet;

public class Example {  
	public static void main(String[] args) {
		HashSet<String> hashSet = new HashSet<String>();
		
		int result = hashSet.size();
		System.out.println("Size of this HashSet is : " + result);
    }  
}

Output

Size of this HashSet is : 0

Example 3 – size() – Modify HashSet

In this example, we will define and initialize a HashSet with four Strings. We will get the size of this HashSet using size() method as 4. We shall them remove two elements and find the size of this HashSet. We will get 2. Now, we will add an element to this HashSet. When we call size() on this HashSet, it will return 3.

Java Program

</>
Copy
import java.util.HashSet;

public class Example {  
	public static void main(String[] args) {
		HashSet<String> hashSet = new HashSet<String>();
		hashSet.add("a");
		hashSet.add("b");
		hashSet.add("c");
		hashSet.add("d");
		
		int result = hashSet.size();
		System.out.println("Size of this HashSet " + hashSet + " is : " + result);
		
		hashSet.remove("c");
		hashSet.remove("d");
		
		result = hashSet.size();
		System.out.println("Size of this HashSet " + hashSet + " is : " + result);
		
		hashSet.add("e");
		result = hashSet.size();
		System.out.println("Size of this HashSet " + hashSet + " is : " + result);
    }  
}

Output

Size of this HashSet [a, b, c, d] is : 4
Size of this HashSet [a, b] is : 2
Size of this HashSet [a, b, e] is : 3

Conclusion

In this Java Tutorial, we have learnt the syntax of Java HashSet.size() method, and also learnt how to use this method with the help of Java examples.