Java程序检查一个集合是否为另一个集合的子集


在本文中,我们将了解如何检查一个集合是否为另一个集合的子集。集合是一个不能包含重复元素的集合。它模拟了数学集合的抽象。集合接口仅包含从集合继承的方法,并增加了禁止重复元素的限制。

以下是演示说明 −

假设我们的输入是

First set: [90, 75, 60, 45]
Second set : [90, 60]

所需的输出是

Is a sets sub-set of the other?
true

算法

Step 1 - START
Step 2 - Declare namely
Step 3 - Define the values.
Step 4 - Create two Sets, and add elements to it using the ‘add’ method.
Step 5 - Display the Sets on the console.
Step 6 - Create a Boolean variable and call the ‘containsAll’ method on one set with respect to the other.
Step 7 - This checks if one set is a subset of the other.
Step 8 - If yes, it returns True, else False.
Step 9 - Display the result on the console.
Step 10 - Stop

示例 1

在这里,我们将所有操作捆绑在“main”函数下。

import java.util.HashSet;
import java.util.Set;
public class Demo {
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      Set<Integer> input_set_1 = new HashSet<>();
      input_set_1.add(45);
      input_set_1.add(60);
      input_set_1.add(75);
      input_set_1.add(90);
      System.out.println("The first set is defined as: " + input_set_1);
      Set<Integer> input_set_2 = new HashSet<>();
      input_set_2.add(60);
      input_set_2.add(90);
      System.out.println("The second set is defined as: " + input_set_2);
      boolean result = input_set_1.containsAll(input_set_2);
      System.out.println("\nIs a sets sub-set of the other? \n" + result);
   }
}

输出

The required packages have been imported
The first set is defined as: [90, 75, 60, 45]
The second set is defined as: [90, 60]

Is a sets sub-set of the other?
true

示例 2

在这里,我们将操作封装到展现面向对象的编程的函数中。

import java.util.HashSet;
import java.util.Set;
public class Demo {
   static void is_subset(Set<Integer> input_set_1, Set<Integer> input_set_2){
      boolean result = input_set_1.containsAll(input_set_2);
      System.out.println("\nIs a sets sub-set of the other? \n" + result);
   }
   public static void main(String[] args) {
      System.out.println("The required packages have been imported");
      Set<Integer> input_set_1 = new HashSet<>();
      input_set_1.add(45);
      input_set_1.add(60);
      input_set_1.add(75);
      input_set_1.add(90);
      System.out.println("The first set is defined as: " + input_set_1);
      Set<Integer> input_set_2 = new HashSet<>();
      input_set_2.add(60);
      input_set_2.add(90);
      System.out.println("The second set is defined as: " + input_set_2);
      is_subset(input_set_1, input_set_1);
   }
}

输出

The required packages have been imported
The first set is defined as: [90, 75, 60, 45]
The second set is defined as: [90, 60]

Is a sets sub-set of the other?
true

更新于:30-Mar-2022

1K+ 浏览量

开始你的职业生涯

完成课程以获得认证

开始
广告