Guava 的Sets.intersection()返回兩個集合的交集的不可更改的視圖。返回的集合包含兩個後備集合都包含的所有元素。返回的集合的迭代順序與set1的迭代順序匹配。
用法:
public static <E> Sets.SetView<E> intersection(Set<E> 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<Integer>
set1 = Sets.newHashSet(10, 20, 30, 40, 50);
// Creating second set
Set<Integer>
set2 = Sets.newHashSet(30, 50, 70, 90);
// Using Guava's Sets.intersection() method
Set<Integer>
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<String>
set1 = Sets.newHashSet("G", "e", "e", "k", "s");
// Creating second set
Set<String>
set2 = Sets.newHashSet("g", "f", "G", "e");
// Using Guava's Sets.intersection() method
Set<String>
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是兩個集合中的較小者時,返回的視圖的性能會稍好一些。如果您有理由相信其中一個集合通常會小於另一個集合,請先通過。
相關用法
- Java Guava Sets powerSet()用法及代碼示例
- Java Guava Sets union()用法及代碼示例
- Java Guava Sets difference()用法及代碼示例
- Java Guava Ints contains()用法及代碼示例
- Java Guava Ints min()用法及代碼示例
- Java Guava Ints max()用法及代碼示例
- Java Guava Ints toArray()用法及代碼示例
- Java Guava BigIntegerMath factorial()用法及代碼示例
- Java Guava BigIntegerMath ceilingPowerOfTwo()用法及代碼示例
- Java Guava BigIntegerMath binomial()用法及代碼示例
- Java Guava BigIntegerMath divide()用法及代碼示例
- Java Guava BigIntegerMath log10()用法及代碼示例
- Java Guava BigIntegerMath floorPowerOfTwo()用法及代碼示例
- Java Guava BigIntegerMath log2()用法及代碼示例
- Java Guava BigIntegerMath isPowerOfTwo()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Sets intersection() function | Guava | Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。