ในบทความนี้ เราจะเข้าใจวิธีการคำนวณจุดตัดของสองชุด ชุดคือคอลเลกชันที่ไม่สามารถมีองค์ประกอบที่ซ้ำกัน มันจำลองชุดนามธรรมที่เป็นนามธรรมของชุดทางคณิตศาสตร์ อินเทอร์เฟซ Set มีเพียงวิธีการที่สืบทอดมาจากคอลเล็กชันและเพิ่มข้อจำกัดที่ห้ามองค์ประกอบที่ซ้ำกัน
ด้านล่างนี้เป็นการสาธิตสิ่งเดียวกัน -
สมมติว่าข้อมูลที่เราป้อนคือ −
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
ที่นี่ เราเชื่อมโยงการดำเนินการทั้งหมดเข้าด้วยกันภายใต้ฟังก์ชัน 'หลัก'
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]