Guava 的Sets.difference()返回無法修改的兩組視圖。
用法:
public static <E> Sets.SetView<E> difference(Set<E> 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<Integer>
set1 = Sets.newHashSet(1, 2, 3, 4, 5, 6);
// Creating second set named set2
Set<Integer>
set2 = Sets.newHashSet(1, 3, 5, 7);
// Using Guava's Sets.difference() method
Set<Integer>
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<String>
set1 = Sets
.newHashSet("H", "E", "L", "L", "O", "G");
// Creating second set named set2
Set<String>
set2 = Sets
.newHashSet("L", "I", "K", "E", "G");
// Using Guava's Sets.difference() method
Set<String>
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]
相關用法
- Java Guava Sets union()用法及代碼示例
- Java Guava Sets powerSet()用法及代碼示例
- Java Guava Sets intersection()用法及代碼示例
- Java Guava Ints max()用法及代碼示例
- Java Guava Ints min()用法及代碼示例
- Java Guava Ints contains()用法及代碼示例
- Java Guava Ints toArray()用法及代碼示例
- Java Guava Ints indexOf()用法及代碼示例
- Java Guava Ints join()用法及代碼示例
- Java Guava Ints concat()用法及代碼示例
- Java Guava Ints lastIndexOf()用法及代碼示例
- Java Guava Ints asList()用法及代碼示例
- Java Guava BigIntegerMath sqrt()用法及代碼示例
- Java Guava BigIntegerMath binomial()用法及代碼示例
- Java Guava BigIntegerMath factorial()用法及代碼示例
注:本文由純淨天空篩選整理自Sahil_Bansall大神的英文原創作品 Sets difference() function | Guava | Java。非經特殊聲明,原始代碼版權歸原作者所有,本譯文未經允許或授權,請勿轉載或複製。