Check if a Java HashSet Collection contains another Collection

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 17-Jan-2019 09:28:23
Advertisements