Guava 的Sets.union()返回两个集合的不可修改的视图。返回的集合包含任一后备集中包含的所有元素。对返回的set进行迭代,首先对set1的所有元素进行迭代,然后依次对set2的每个元素进行迭代,这些迭代不包含在set1中。
用法:
public static <E> Sets.SetView<E> union(Set<? extends E> set1, Set<? extends E> set2)
返回值:此方法返回两个集合的不可修改的视图。
范例1:
// Java code to show implementation
// of Guava's Sets.union() 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(1, 2, 3, 4, 5);
// Creating second set
Set<Integer>
set2 = Sets.newHashSet(3, 5, 7, 9);
// Using Guava's Sets.union() method
Set<Integer>
answer = Sets.union(set1, set2);
// Displaying the union of set set1 and set2
System.out.println("Set 1:"
+ set1);
System.out.println("Set 2:"
+ set2);
System.out.println("Set 1 union Set 2:"
+ answer);
}
}
输出:
Set 1:[1, 2, 3, 4, 5] Set 2:[9, 3, 5, 7] Set 1 union Set 2:[1, 2, 3, 4, 5, 9, 7]
范例2:
// Java code to show implementation
// of Guava's Sets.union() 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.union() method
Set<String>
answer = Sets.union(set1, set2);
// Displaying the union of set set1 and set2
System.out.println("Set 1:"
+ set1);
System.out.println("Set 2:"
+ set2);
System.out.println("Set 1 union Set 2:"
+ answer);
}
}
输出:
Set 1:[k, s, e, G] Set 2:[e, f, g, G] Set 1 union Set 2:[k, s, e, G, f, g]
相关用法
- Java Guava Sets powerSet()用法及代码示例
- Java Guava Sets intersection()用法及代码示例
- Java Guava Sets difference()用法及代码示例
- Java Guava Ints min()用法及代码示例
- Java Guava Ints contains()用法及代码示例
- Java Guava Ints max()用法及代码示例
- Java Guava Ints asList()用法及代码示例
- Java Guava BigIntegerMath floorPowerOfTwo()用法及代码示例
- Java Guava BigIntegerMath log10()用法及代码示例
- Java Guava BigIntegerMath log2()用法及代码示例
- Java Guava BigIntegerMath sqrt()用法及代码示例
- Java Guava BigIntegerMath binomial()用法及代码示例
- Java Guava BigIntegerMath divide()用法及代码示例
- Java Guava BigIntegerMath isPowerOfTwo()用法及代码示例
- Java Guava Ints join()用法及代码示例
注:本文由纯净天空筛选整理自Sahil_Bansall大神的英文原创作品 Sets union() function | Guava | Java。非经特殊声明,原始代码版权归原作者所有,本译文未经允许或授权,请勿转载或复制。