- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
Count the number of elements in a HashSet in Java
To count the number of elements in a HashSet, use the size() method.
Create HashSet −
String strArr[] = { "P", "Q", "R" }; Set s = new HashSet(Arrays.asList(strArr));
Let us now count the number of elements in the above Set −
s.size()
The following is an example to count the number of elements in a HashSet −
Example
import java.util.Arrays; import java.util.HashSet; import java.util.Set; public class Demo { public static void main(String[] a) { String strArr[] = { "P", "Q", "R" }; Set s = new HashSet(Arrays.asList(strArr)); System.out.println("Elements: "+s); System.out.println("Number of Elements: "+s.size()); } }
Output
Elements: [P, Q, R] Number of Elements: 3
Let us see another example −
Example
import java.util.*; public class Demo { public static void main(String args[]) { // create a hash set HashSet hs = new HashSet(); // add elements to the hash set hs.add("B"); hs.add("A"); hs.add("D"); hs.add("E"); hs.add("C"); hs.add("F"); hs.add("K"); hs.add("M"); hs.add("N"); System.out.println("Elements: "+hs); System.out.println("Number of Elements: "+hs.size()); } }
Output
Elements: [A, B, C, D, E, F, K, M, N] Number of Elements: 9
- Related Articles
- Number of elements in HashSet in C#?
- Iterate over the elements of HashSet in Java
- Iterate through elements of HashSet in Java
- Add elements to HashSet in Java
- Remove all elements from a HashSet in Java
- Remove duplicate elements in Java with HashSet
- Convert elements in a HashSet to an array in Java
- Add all the elements from a collection to the HashSet in Java
- Count the number of masked elements in Numpy
- The HashSet in Java
- Get the count of elements in HashMap in Java
- Count the total number of elements in the List in C#?
- Importance of HashSet in Java
- HashSet in Java
- Count the number of masked elements along axis 0 to count in Numpy

Advertisements