Java 计算两个集合的并集

Java 计算两个集合的并集

在本文章中,我们将了解如何计算两个集合的并集。集合是一种不能包含重复元素的集合,它模拟了数学中的集合抽象概念。Set接口只包含了从Collection继承而来的方法,并添加了重复元素被禁止的限制。

以下是相同计算的演示 −

**假设我们的输入是: −

First set: [2, 4]
Second set: [1, 3]

期望得到的输出将是:

The union of the two sets is:
[1, 2, 3, 4]

步骤

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 - Add both the sets using the ‘addAll’ method.
Step 7 - Display the sum of sets on the console.
Step 8 - 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(2);
      input_set_1.add(4);
      System.out.println("The first set is defined as: " + input_set_1);
      Set<Integer> input_set_2 = new HashSet<>();
      input_set_2.add(1);
      input_set_2.add(3);
      System.out.println("The second set is defined as: " + input_set_2);
      input_set_2.addAll(input_set_1);
      System.out.println("\nThe union of the two sets is: \n" + input_set_2);
   }
}

输出

The required packages have been imported
The first set is defined as: [2, 4]
The second set is defined as: [1, 3]

The union of the two sets is:
[1, 2, 3, 4]

示例2

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

import java.util.HashSet;
import java.util.Set;
public class Demo {
   static void union_sets(Set<Integer> input_set_1, Set<Integer> input_set_2){
      input_set_2.addAll(input_set_1);
      System.out.println("\nThe union of the two sets is: \n" + input_set_2);
   }
   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(2);
      input_set_1.add(4);
      System.out.println("The first set is defined as: " + input_set_1);
      Set<Integer> input_set_2 = new HashSet<>();
      input_set_2.add(1);
      input_set_2.add(3);
      System.out.println("The second set is defined as: " + input_set_2);
      union_sets(input_set_1, input_set_2);
   }
}

输出

The required packages have been imported
The first set is defined as: [2, 4]
The second set is defined as: [1, 3]

The union of the two sets is:
[1, 2, 3, 4]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程