Java Collection How to - Find out how many elements are in a set, check if a set is empty








Question

We would like to know how to find out how many elements are in a set, check if a set is empty.

Answer

      
import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/*from   w ww.ja v  a  2s . c o m*/
public class MainClass {

  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));

    System.out.println(set.size());
  }
}

Checking for no elements in the set: use the isEmpty() method instead

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/* w ww .  ja va2 s  .  c  om*/
public class MainClass {

  public static void main(String[] a) {
    String elements[] = { "A", "B", "C", "D", "E" };
    Set set = new HashSet(Arrays.asList(elements));

    System.out.println(set.isEmpty());
  }
}

The code above generates the following result.