Trong bài này, chúng ta sẽ hiểu cách tính giao hai Set. Set là Collection không chứa phần tử trùng lặp, mô hình hóa tập hợp toán học.
Dưới đây là minh họa:
Giả sử đầu vào:
Tập 1: [40, 45] Tập 2: [50, 45]
Đầu ra mong muốn:
Giao hai tập là: [45]
Thuật toán
Bước 1 - BẮT ĐẦU Bước 2 - Khai báo... Bước 3 - Định nghĩa giá trị. Bước 4 - Tạo 2 Set, thêm phần tử bằng 'add'. Bước 5 - Hiển thị Set ra console. Bước 6 - Tính giao tập dùng 'retainAll'. Bước 7 - Hiển thị giao (phần tử chung) hai tập. Bước 8 - KẾT THÚC
Ví dụ 1
Gom 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("Các gói cần thiết đã được import");
Set<Integer> input_set_1 = new HashSet<>();
input_set_1.add(40);
input_set_1.add(45);
System.out.println("Tập 1 định nghĩa: " + input_set_1);
Set<Integer> input_set_2 = new HashSet<>();
input_set_2.add(45);
input_set_2.add(50);
System.out.println("Tập 2 định nghĩa: " + input_set_2);
input_set_2.retainAll(input_set_1);
System.out.println("\nGiao hai tập là: " + input_set_2);
}
}
Kết quả
Các gói cần thiết đã được import Tập 1 định nghĩa: [40, 45] Tập 2 định nghĩa: [50, 45] Giao hai tập là: [45]
Ví dụ 2
Đóng gói thao tác vào hàm thể hiện OOP.
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("\nGiao hai tập là: " + input_set_2);
}
public static void main(String[] args) {
System.out.println("Các gói cần thiết đã được import");
Set<Integer> input_set_1 = new HashSet<>();
input_set_1.add(40);
input_set_1.add(45);
System.out.println("Tập 1 định nghĩa: " + input_set_1);
Set<Integer> input_set_2 = new HashSet<>();
input_set_2.add(45);
input_set_2.add(50);
System.out.println("Tập 2 định nghĩa: " + input_set_2);
set_intersection(input_set_1, input_set_2);
}
}
Kết quả
Các gói cần thiết đã được import Tập 1 định nghĩa: [40, 45] Tập 2 định nghĩa: [50, 45] Giao hai tập là: [45]