设置差异()函数|番石榴 |Java
Guava 的Sets.difference()返回两个集合差异的不可修改视图。
句法:
public static
Sets.SetView
difference(Set set1,
Set> set2)
返回值:此方法返回一个集合,该集合包含 set1 包含但 set2 不包含的所有元素。
注意: Set2 也可能包含 set1 中不存在的元素,这些被简单地忽略。返回集合的迭代顺序与 set1 的迭代顺序一致。
示例 1:
// Java code to show implementation of
// Guava's Sets.difference() 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 named set1
Set
set1 = Sets.newHashSet(1, 2, 3, 4, 5, 6);
// Creating second set named set2
Set
set2 = Sets.newHashSet(1, 3, 5, 7);
// Using Guava's Sets.difference() method
Set
diff = Sets.difference(set1, set2);
// Displaying the unmodifiable view of
// the difference of two sets.
System.out.println("Set 1: "
+ set1);
System.out.println("Set 2: "
+ set2);
System.out.println("Difference between "
+ "Set 1 and Set 2: "
+ diff);
}
}
输出:
Set 1: [1, 2, 3, 4, 5, 6]
Set 2: [1, 3, 5, 7]
Difference between Set 1 and Set 2: [2, 4, 6]
示例 2:
// Java code to show implementation of
// Guava's Sets.difference() 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 named set1
Set
set1 = Sets
.newHashSet("H", "E", "L", "L", "O", "G");
// Creating second set named set2
Set
set2 = Sets
.newHashSet("L", "I", "K", "E", "G");
// Using Guava's Sets.difference() method
Set
diff = Sets.difference(set1, set2);
// Displaying the unmodifiable view of
// the difference of two sets.
System.out.println("Set 1: "
+ set1);
System.out.println("Set 2: "
+ set2);
System.out.println("Difference between "
+ "Set 1 and Set 2: "
+ diff);
}
}
输出:
Set 1: [E, G, H, L, O]
Set 2: [I, K, L, E, G]
Difference between Set 1 and Set 2: [H, O]