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 −
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()); } }
Elements = [82, 71, 89, 91, 15] Size of Set: 5 Updated Elements = [71, 89, 15] Size of Set now: 3