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("
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

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

235 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements