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

 Live Demo

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("\nUpdated 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
Updated on: 2020-06-25T09:48:14+05:30

366 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements