ในบทความนี้ เราจะเข้าใจวิธีคำนวณความต่างระหว่างสอง Set Set คือ Collection ที่ไม่สามารถมี duplicate elements ได้ มันเป็นแบบจำลองของ mathematical set abstraction อินเตอร์เฟซ Set มีเฉพาะเมธอดที่สืบทอดจาก Collection และเพิ่มข้อจำกัดว่าห้ามมี duplicate elements
ด้านล่างเป็นการสาธิต:
สมมติอินพุตคือ
First set: [90, 75, 60, 45] Second set: [90, 60]
เอาต์พุตที่ต้องการคือ
After subtraction of two sets: [75, 45]
อัลกอริทึม
Step 1 - START Step 2 - ประกาศตัวแปร Step 3 - กำหนดค่า Step 4 - สร้าง 2 Sets เพิ่มองค์ประกอบด้วย 'add' Step 5 - แสดง Sets บนคอนโซล Step 6 - คำนวณความต่างของ sets ด้วยเมธอด 'removeAll' Step 7 - แสดงความต่างของ sets บนคอนโซล 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 input_set_1 = new HashSet<>();
input_set_1.add(45);
input_set_1.add(60);
input_set_1.add(75);
input_set_1.add(90);
System.out.println("The first set is defined as: " + input_set_1);
Set input_set_2 = new HashSet<>();
input_set_2.add(60);
input_set_2.add(90);
System.out.println("The second set is defined as: " + input_set_2);
input_set_1.removeAll(input_set_2);
System.out.println("\nAfter subtraction of two sets: \n" + input_set_1);
}
}
ผลลัพธ์
The required packages have been imported The first set is defined as: [90, 75, 60, 45] The second set is defined as: [90, 60] After subtraction of two sets: [75, 45]
ตัวอย่าง 2
ที่นี่ เราบรรจุการดำเนินการลงในฟังก์ชันแสดง object-oriented programming
import java.util.HashSet;
import java.util.Set;
public class Demo {
static void subtract(Set input_set_1, Set input_set_2){
input_set_1.removeAll(input_set_2);
System.out.println("\nAfter subtraction of two sets: \n" + input_set_1);
}
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(45);
input_set_1.add(60);
input_set_1.add(75);
input_set_1.add(90);
System.out.println("The first set is defined as: " + input_set_1);
Set input_set_2 = new HashSet<>();
input_set_2.add(60);
input_set_2.add(90);
System.out.println("The second set is defined as: " + input_set_2);
subtract(input_set_1, input_set_2);
}
}
ผลลัพธ์
The required packages have been imported The first set is defined as: [90, 75, 60, 45] The second set is defined as: [90, 60] After subtraction of two sets: [75, 45]