Computer >> Máy Tính >  >> Lập trình >> Java

Chương trình Java để tính toán giao của hai tập hợp

Trong bài này, chúng ta sẽ hiểu làm thế nào để tính toán giao của hai tập hợp. Một Tập hợp là một Bộ sưu tập không thể chứa các phần tử trùng lặp. Nó lập mô hình trừu tượng hóa tập hợp toán học. Giao diện Set chỉ chứa các phương thức được kế thừa từ Collection và thêm các hạn chế rằng các phần tử trùng lặp bị cấm.

Dưới đây là một minh chứng về điều tương tự -

Giả sử đầu vào của chúng tôi là -

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

Đầu ra mong muốn sẽ là -

The intersection of two sets is: [45]

Thuật toán

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

Ví dụ 1

Ở đây, chúng tôi liên kết tất cả các hoạt động với nhau trong hàm "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);
   }
}

Đầu ra

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]

Ví dụ 2

Ở đây, chúng tôi đóng gói các hoạt động thành các hàm trưng bày lập trình hướng đối tượng.

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

Đầu ra

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]