- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- 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
Get size of HashSet in Java
To get the size of HashSet, use the size() method. Let us create a HashSet and add elements −
Set<Integer> hs = new HashSet<Integer>(); hs.add(15); hs.add(71); hs.add(82); hs.add(89); hs.add(91);
Let us now use size() and get the size of HashSet −
hs.size()
The following is an example to get the size of HashSet −
Example
import java.util.*; public class Demo { public static void main(String args[]) { Set<Integer> hs = new HashSet<Integer>(); hs.add(15); hs.add(71); hs.add(82); hs.add(89); hs.add(91); System.out.println("Elements = "+hs); System.out.println("Size of Set: "+hs.size()); hs.remove(82); hs.remove(91); System.out.println("
Updated Elements = "+hs); System.out.println("Size of Set now: "+hs.size()); } }
Output
Elements = [82, 71, 89, 91, 15] Size of Set: 5 Updated Elements = [71, 89, 15] Size of Set now: 3
Advertisements