设置交集()函数|番石榴 |Java
Guava 的Sets.intersection()返回两个集合交集的不可修改视图。返回的集合包含两个支持集合所包含的所有元素。返回集合的迭代顺序与 set1 的迭代顺序一致。
句法:
public static
Sets.SetView
intersection(Set set1, Set> set2)
返回值:此方法返回两个集合交集的不可修改视图。
以下示例说明了 Sets 交集方法的工作原理:
示例 1:
// Java code to show implementation
// of Guava's Sets.intersection() method
import com.google.common.collect.Sets;
import java.util.Set;
class GFG {
// Driver's code
public static void main(String[] args)
{
// Creating first set
Set
set1 = Sets.newHashSet(10, 20, 30, 40, 50);
// Creating second set
Set
set2 = Sets.newHashSet(30, 50, 70, 90);
// Using Guava's Sets.intersection() method
Set
answer = Sets.intersection(set1, set2);
// Displaying the intersection of set1 and set2
System.out.println("Set 1: "
+ set1);
System.out.println("Set 2: "
+ set2);
System.out.println("Set 1 intersection Set 2: "
+ answer);
}
}
输出:
Set 1: [40, 10, 50, 20, 30]
Set 2: [50, 90, 30, 70]
Set 1 intersection Set 2: [50, 30]
示例 2:
// Java code to show implementation
// of Guava's Sets.intersection() method
import com.google.common.collect.Sets;
import java.util.Set;
class GFG {
// Driver's code
public static void main(String[] args)
{
// Creating first set
Set
set1 = Sets.newHashSet("G", "e", "e", "k", "s");
// Creating second set
Set
set2 = Sets.newHashSet("g", "f", "G", "e");
// Using Guava's Sets.intersection() method
Set
answer = Sets.intersection(set1, set2);
// Displaying the intersection of set1 and set2
System.out.println("Set 1: "
+ set1);
System.out.println("Set 2: "
+ set2);
System.out.println("Set 1 intersection Set 2: "
+ answer);
}
}
输出:
Set 1: [k, s, e, G]
Set 2: [e, f, g, G]
Set 1 intersection Set 2: [e, G]
注意:当 set1 是两个集合中较小的一个时,返回的视图性能稍好。如果您有理由相信您的一组通常会比另一组小,请先通过它。