溫馨提示×

如何用Java找出兩個集合的交集

小樊
86
2024-08-23 09:22:28
欄目: 編程語言

可以使用Java中的Collection類的retainAll()方法來找出兩個集合的交集。下面是一個示例代碼:

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

public class Main {
    public static void main(String[] args) {
        Set<Integer> set1 = new HashSet<>();
        set1.add(1);
        set1.add(2);
        set1.add(3);

        Set<Integer> set2 = new HashSet<>();
        set2.add(2);
        set2.add(3);
        set2.add(4);

        Set<Integer> intersection = new HashSet<>(set1);
        intersection.retainAll(set2);

        System.out.println("Intersection of set1 and set2: " + intersection);
    }
}

在這個示例中,我們首先創(chuàng)建了兩個HashSet集合set1和set2,然后使用retainAll()方法找到這兩個集合的交集,并將結(jié)果存儲在一個新的HashSet集合intersection中。最后,輸出交集的結(jié)果。

0