编写程序求三个集合的交集

发布网友 发布时间:2022-04-21 07:04

我来回答

1个回答

热心网友 时间:2022-06-18 14:46

public class Test {

public static void main(String args[])
{
Set<Integer> a = new HashSet<Integer>(Arrays.asList(1, 2, 3, 4, 5));
Set<Integer> b = new HashSet<Integer>(Arrays.asList(3, 4, 6, 7, 8));
Set<Integer> c = new HashSet<Integer>(Arrays.asList(4, 5, 8, 9, 0));
Set<Integer> aIntersectsB = intersects(a, b);
Set<Integer> aIntersectsC = intersects(a, c);
Set<Integer> bIntersectsC = intersects(b, c);
Set<Integer> abc = intersects(a, bIntersectsC);

System.out.println("a ∩ b: " + aIntersectsB);
System.out.println("a ∩ c: " + aIntersectsC);
System.out.println("b ∩ c: " + bIntersectsC);
System.out.println("a ∩ b ∩ c: " + abc);
}

private static <E> Set<E> intersects(Set<E> set1, Set<E> set2) {
Set<E> intersectSet = new HashSet<E>(set1);
intersectSet.retainAll(set2);
return intersectSet;
}

}

声明声明:本网页内容为用户发布,旨在传播知识,不代表本网认同其观点,若有侵权等问题请及时与本网联系,我们将在第一时间删除处理。E-MAIL:11247931@qq.com