📜  设置 union()函数|番石榴 |Java

📅  最后修改于: 2022-05-13 01:55:41.800000             🧑  作者: Mango

设置 union()函数|番石榴 |Java

Guava 的Sets.union()返回两个集合并集的不可修改视图。返回的集合包含任一支持集合中包含的所有元素。遍历返回的集合首先遍历 set1 的所有元素,然后依次遍历 set2 的每个元素,即不包含在 set1 中的元素。

句法:

public static  
  Sets.SetView 
    union(Set set1, 
          Set 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
            set1 = Sets.newHashSet(1, 2, 3, 4, 5);
  
        // Creating second set
        Set
            set2 = Sets.newHashSet(3, 5, 7, 9);
  
        // Using Guava's Sets.union() method
        Set
            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
            set1 = Sets.newHashSet("G", "e", "e", "k", "s");
  
        // Creating second set
        Set
            set2 = Sets.newHashSet("g", "f", "G", "e");
  
        // Using Guava's Sets.union() method
        Set
            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]