Count the number of elements in a HashSet in Java

Java 8Object Oriented ProgrammingProgramming

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

 Live Demo

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

 Live Demo

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
raja
Updated on 25-Jun-2020 07:21:19

Advertisements