Write a Java program to get the number of elements in a hash set


In the program, a HashSet named h_set is created and populated with some elements: "Blue", "Green", "Black", "Orange", "White", "Pink", and "Yellow". The program then uses the size() method to get the number of elements in h_set. The size() method returns an integer representing the number of elements in the HashSet. Finally, the program prints the number of elements in h_set to the console.

Source Code

import java.util.*;
import java.util.Iterator;
public class GetNumber_Elements
{
	public static void main(String[] args)
	{
		HashSet<String> h_set = new HashSet<String>();
		h_set.add("Blue");
		h_set.add("Green");
		h_set.add("Black");
		h_set.add("Orange");
		h_set.add("White");
		h_set.add("Pink");
		h_set.add("Yellow");
		System.out.println("Given HashSet : " + h_set);	
		System.out.println("Number of Elements in Hash Set : " + h_set.size());
	}
}

Output

Given HashSet : [White, Pink, Blue, Yellow, Black, Orange, Green]
Number of Elements in Hash Set : 7

Example Programs