Java Collection How to - Check for Existence for a single value or a subset








Question

We would like to know how to check for Existence for a single value or a subset.

Answer

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
//  w  w  w  . ja va  2s  .  co  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.contains("A"));
  }
}

The code above generates the following result.

the containsAll() method checks if a set contains another whole collection

import java.util.Arrays;
import java.util.HashSet;
import java.util.Set;
/*from w w  w. java  2 s . co m*/
public class MainClass {

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

    elements = new String[] { "A", "B", "C" };
    Set set2 = new HashSet(Arrays.asList(elements));

    System.out.println(set.containsAll(set2));
  }
}

The code above generates the following result.