功能
返回两个集合差异的不可修改视图
用法
Set<E> difference=Sets.difference(set1,set2);
此方法返回一个差集,该集合里边是(set1 包含但 set2 不包含的所有元素)。
注意: Set2 也可能包含 set1 中不存在的元素,这些被简单地忽略。返回集合的迭代顺序与 set1 的迭代顺序一致。
示例1
import com.google.common.collect.Sets;
import java.util.Set;
class Diff{
public static void main(String[] args)
{
Set<Integer> set1 = Sets.newHashSet(1, 2, 3, 4, 5, 6);
Set<Integer> set2 = Sets.newHashSet(1, 3, 5, 7);
Set<Integer> difference = Sets.difference(set1, set2);
System.out.println("Set 1: + set1);
System.out.println("Set 2: + set2);
System.out.println(“Set 1 和 Set 2的差异: "+ difference);
}
}
输出:
Set 1:[1, 2, 3, 4, 5, 6]
Set 2:[1, 3, 5, 7]
Set 1 和 Set 2之间的差异:[2, 4, 6]
示例2
import com.google.common.collect.Sets;
import java.util.Set;
class Diff2{
public static void main(String[] args)
{
Set<String> set1 = Sets.newHashSet("H", "E", "L", "L", "O", "G");
Set<String> set2 = Sets.newHashSet("L", "I", "K", "E", "G");
Set<String> difference2 = Sets.difference(set1, set2);
System.out.println("Set 1: "+ set1);
System.out.println("Set 2: "+ set2);
System.out.println("Set 1 和 Set 2的差异: "+ difference2);
}
}
输出:
Set 1:[E、G、H、L、O]
Set 2:[I、K、L、E、G]
Set 1 和 Set 2的差异:[H、O]