Check if a Java HashSet Collection contains another Collection


To check whether a HashSet contains another, use the contains() method.

Set the first HashSet

String strArr[] = { "P", "Q", "R" };
Set set1 = new HashSet(Arrays.asList(strArr));

Set the second HashSet

String strArr = new String[] { "P", "Q"};
Set set2 = new HashSet(Arrays.asList(strArr));

Check now

set1.containsAll(set2))

The following is an example to check if a HashSet collection in Java contains another Collection

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 set1 = new HashSet(Arrays.asList(strArr));
      strArr = new String[] { "P", "Q"};
      Set set2 = new HashSet(Arrays.asList(strArr));
      System.out.println(set1.containsAll(set2));
      strArr = new String[] { "T", "U"};
      Set set3 = new HashSet(Arrays.asList(strArr));
      System.out.println(set1.containsAll(set3));
   }
}

The following is the output

true
false

Updated on: 30-Jul-2019

809 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements