檢查 Java HashSet 集合中是否包含另一個集合


要檢查 HashSet 是否包含另一個 HashSet,請使用 contains() 方法。

設定第一個 HashSet

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

設定第二個 HashSet

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

現在檢查

set1.containsAll(set2))

以下是如何檢查 Java 中的 HashSet 集合是否包含另一個集合的示例

示例

 動態演示

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));
   }
}

以下是輸出

true
false

更新於: 30-07-2019

885 次瀏覽

啟動您的 事業

完成課程並獲得認證

開始
廣告
© . All rights reserved.