
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
- 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 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
Advertisements