Computer >> Hướng Dẫn Máy Tính >  >> Lập Trình >> Java

Chương trình Java tính hợp (union) của hai tập hợp (Set)


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

Minh họa dưới đây:

Giả sử đầu vào là:

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

Đầu ra mong muốn:

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

Thuật toán

Bước 1 - BẮT ĐẦU 
Bước 2 - Khai báo biến 
Bước 3 - Định nghĩa giá trị 
Bước 4 - Tạo hai Set, thêm phần tử bằng phương thức 'add' 
Bước 5 - Hiển thị Set trên console 
Bước 6 - Gộp hai set bằng phương thức 'addAll' 
Bước 7 - Hiển thị kết quả hợp trên console 
Bước 8 - DỪNG

Ví dụ 1

Ở đây, chúng ta gom tất cả các thao tác dưới 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 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 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); 
    } 
}

Kết quả

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]

Ví dụ 2

Ở đây, chúng ta đóng gói các thao tác vào các hàm thể hiện lập trình hướng đối tượng.

import java.util.HashSet; 
import java.util.Set; 

public class Demo { 
    static void union_sets(Set input_set_1, Set 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 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 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); 
    } 
}

Kết quả

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]