Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Java

Java Program: คำนวณ Intersection ของสอง Set


ในบทความนี้ เราจะเข้าใจวิธีคำนวณ Intersection ของสอง Set Set คือ Collection ที่ไม่สามารถมี duplicate elements ได้ มันเป็นแบบจำลองของ mathematical set abstraction อินเตอร์เฟซ Set มีเฉพาะเมธอดที่สืบทอดจาก Collection และเพิ่มข้อจำกัดว่าห้ามมี duplicate elements

ด้านล่างเป็นการสาธิต:

สมมติอินพุตคือ

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

เอาต์พุตที่ต้องการคือ

The intersection of two sets is: [45]

อัลกอริทึม

Step 1 - START
Step 2 - ประกาศตัวแปร
Step 3 - กำหนดค่า
Step 4 - สร้าง 2 Sets เพิ่มองค์ประกอบด้วย 'add'
Step 5 - แสดง Sets บนคอนโซล
Step 6 - คำนวณ intersection ของ sets ด้วยเมธอด 'retainAll'
Step 7 - แสดง intersection (องค์ประกอบที่ซ้ำกัน) ของทั้งสอง 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(40);
        input_set_1.add(45);
        System.out.println("The first set is defined as: " + input_set_1);
        Set 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

ที่นี่ เราบรรจุการดำเนินการลงในฟังก์ชันแสดง object-oriented programming

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

public class Demo {
    static void set_intersection(Set input_set_1, Set 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 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 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]