Java 计算两个集合的交集

Java 计算两个集合的交集

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

下面是同样内容的演示示例 −

假设我们的输入是

First set: [40, 45]
Second set: [50, 45]

期望的输出是 -

The intersection of two sets is: [45]

步骤

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 - Compute the intersection of the sets using the ‘retainAll’ method.
Step 7 - Display the intersection (all the unique elements) of both the 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(40);
      input_set_1.add(45);
      System.out.println("The first set is defined as: " + input_set_1);
      Set<Integer> input_set_2 = new HashSet<>();
      input_set_2.add(45);
      input_set_2.add(50);
      System.out.println("The second set is defined as: " + input_set_2);
      input_set_2.retainAll(input_set_1);
      System.out.println("\nThe intersection of two sets is: " + input_set_2);
   }
}

输出

The required packages have been imported
The first set is defined as: [40, 45]
The second set is defined as: [50, 45]

The intersection of two sets is: [45]

示例2

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

import java.util.HashSet;
import java.util.Set;
public class Demo {
   static void set_intersection(Set<Integer> input_set_1, Set<Integer> input_set_2){
      input_set_2.retainAll(input_set_1);
      System.out.println("\nThe intersection of two sets is: " + 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(40);
      input_set_1.add(45);
      System.out.println("The first set is defined as: " + input_set_1);
      Set<Integer> input_set_2 = new HashSet<>();
      input_set_2.add(45);
      input_set_2.add(50);
      System.out.println("The second set is defined as: " + input_set_2);
      set_intersection(input_set_1, input_set_2);
   }
}

输出

The required packages have been imported
The first set is defined as: [40, 45]
The second set is defined as: [50, 45]

The intersection of two sets is: [45]

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程