La interfaz set está presente en el paquete java.util y amplía la interfaz Collection, que es una colección desordenada de objetos en los que no se pueden almacenar valores duplicados. Es una interfaz que implementa el conjunto matemático. Esta interfaz contiene los métodos heredados de la interfaz Collection y agrega una función que restringe la inserción de elementos duplicados. Hay dos interfaces que amplían la implementación del conjunto, a saber, SortedSet y NavigableSet .
Métodos: Las siguientes son las diversas formas de fusionar dos conjuntos en Java:
- Usando la inicialización de doble llave
- Usando el método addAll() de la clase Set
- Usando el método definido por el usuario
- Usando el flujo de Java 8 en la función definida por el usuario
- Usando el flujo de Java 8 en la función definida por el usuario
- Uso de los métodos of() y forEach() de la clase Stream
- Usando el método of() y flatMap() de la clase Stream con Collector
- Usando el método concat() de Stream Class con Collector
- Uso de colecciones comunes de Apache
- Usando Guayaba Iterables.concat()
Método 1: Uso de la inicialización de doble llave
Ilustración:
Input : a = [1, 3, 5, 7, 9] b = [0, 2, 4, 6, 8] Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Ejemplo
Java
// Java Program to Demonstrate Merging of two sets in Java // Using Double brace Initialization // Importing required classes import java.io.*; import java.util.*; import java.util.stream.*; // Main class public class GFG { // Method 1 // To merge two sets // using DoubleBrace Initialisation public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding all elements of respective Sets // using addAll() method return new HashSet<T>() { { addAll(a); addAll(b); } }; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); // Applying Arrays.asList() a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); // Applying Arrays.asList() b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling Method 1 to merge above Sets System.out.println("Merged Set: " + mergeSet(a, b)); } }
Set a: [1, 3, 5, 7, 9] Set b: [0, 2, 4, 6, 8] Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Método 2: Usar el método addAll() de la clase Set
El método addAll() lo proporciona la interfaz Set. Agrega los elementos pasados como parámetros en el último de este conjunto.
2-A. Usando el método definido por el usuario
Ilustración:
Input : a = [1, 3, 5, 7, 9] b = [0, 2, 4, 6, 8] Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Ejemplo:
Java
// Java program to demonstrate Merging of Two Sets // Using SetAll() method // Importing required classes import java.util.*; // Main class public class GFG { // Method 1 // To merge two sets // using addAll() public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Creating an empty HashSet Set<T> mergedSet = new HashSet<T>(); // Adding the two sets to be merged // into the new Set using addAll() method mergedSet.addAll(a); mergedSet.addAll(b); // Returning the merged set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First Set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second Set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge above Sets // and printing it System.out.println("Merged Set: " + mergeSet(a, b)); } }
Set a: [1, 3, 5, 7, 9] Set b: [0, 2, 4, 6, 8] Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
2-B. Usando el flujo de Java 8 en la función definida por el usuario
Ilustración:
Input : a = [1, 3, 5, 7, 9] b = [0, 2, 4, 6, 8] Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Ejemplo
Java
// Java program to demonstrate Merging of Two Sets // Using Stream // Importing required classes import java.io.*; import java.util.*; import java.util.stream.*; // Main class public class GFG { // Method 1 // To merge two Sets // using addAll() public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Creating a Set with 'a' Set<T> mergedSet = a.stream().collect(Collectors.toSet()); // Adding the second set to be merged mergedSet.addAll(b); // Returning the merged Set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the Sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing above Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge two Sets System.out.println("Merged Set: " + mergeSet(a, b)); } }
Set a: [1, 3, 5, 7, 9] Set b: [0, 2, 4, 6, 8] Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Método 3: Usar el método addAll() de la clase Collections
Ilustración:
Input : a = [1, 3, 5, 7, 9] b = [0, 2, 4, 6, 8] Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Ejemplo:
Java
// Java Program to Merge Two Arrays // of Same Type into an Object Array // Importing required classes import java.io.*; import java.util.*; // Main class class GFG { // Method 1 // To merging two Sets // using addAll() public static Set<Integer> mergeSet(Set<Integer> a, Set<Integer> b) { // Creating an empty HashSet of Integer type Set<Integer> mergedSet = new HashSet<>(); // Adding the two sets to be merged // into the new Set Collections.addAll(mergedSet, a.toArray(new Integer[0])); Collections.addAll(mergedSet, b.toArray(new Integer[0])); // Returning the merged Set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling above method 1 to merge two sets System.out.println("Merged Set: " + mergeSet(a, b)); } }
Set a: [1, 3, 5, 7, 9] Set b: [0, 2, 4, 6, 8] Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Método 4: Uso de los métodos of() y forEach() de la clase Stream
Ilustración:
Input : a = [1, 3, 5, 7, 9] b = [0, 2, 4, 6, 8] Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Ejemplo:
Java
// Java Program to Demonstrate Merging of Two Sets // Using Stream // Importing required classes import java.io.*; import java.util.*; import java.util.stream.*; // Main class public class GFG { // Method 1 // To merge two sets // using Stream of() and forEach() methods public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Creating an empty set Set<T> mergedSet = new HashSet<T>(); // add the two sets to be merged // into the new set Stream.of(a, b).forEach(mergedSet::addAll); // returning the merged set return mergedSet; } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge two Sets System.out.println("Merged Set: " + mergeSet(a, b)); } }
Set a: [1, 3, 5, 7, 9] Set b: [0, 2, 4, 6, 8] Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Método 5: Usar el método of() y flatMap() de la clase Stream con Collector
Ilustración:
Input : a = [1, 3, 5, 7, 9] b = [0, 2, 4, 6, 8] Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Ejemplo:
Java
// Java Program to Demonstrate Merging of Two Sets // Using stream // Importing required classes import java.io.*; import java.util.*; import java.util.stream.*; // Main class public class GFG { // Method 1 // To merge two Sets // using Stream of(), flatMap() and Collector public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two Sets to be merged // into the new Set and // returning the merged set return Stream.of(a, b) .flatMap(x -> x.stream()) .collect(Collectors.toSet()); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First Set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second Set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge above two Sets System.out.println("Merged Set: " + mergeSet(a, b)); } }
Set a: [1, 3, 5, 7, 9] Set b: [0, 2, 4, 6, 8] Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Método 6: Usar el método concat() de Stream Class con Collector
Ilustración:
Input : a = [1, 3, 5, 7, 9] b = [0, 2, 4, 6, 8] Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
La función de concatenación se usa para fusionar una string y hacer una sola string que contenga ambas strings. El método Stream.concat() crea un flujo concatenado perezosamente cuyos elementos son todos los elementos del primer flujo seguidos por todos los elementos del segundo flujo.
Ejemplo
Java
// Java program to Demonstrate Merging of two Sets // using Stream // Importing required classes import java.io.*; import java.util.*; import java.util.stream.*; // Main class public class GFG { // Method 1 // To merge two sets // using Stream concat() and Collectors public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two sets to be merged // into the new Set and // returning the merged set return Stream.concat(a.stream(), b.stream()) .collect(Collectors.toSet()); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the sets to be merged // First Set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second Set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling the method 1 to merge two Sets System.out.println("Merged Set: " + mergeSet(a, b)); } }
Set a: [1, 3, 5, 7, 9] Set b: [0, 2, 4, 6, 8] Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Método 7: uso de las colecciones comunes de Apache
Ilustración:
Input : a = [1, 3, 5, 7, 9] b = [0, 2, 4, 6, 8] Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Ejemplo
Java
// Java Program to Demonstrate Merging of Two Sets // Using Apache Common Collection // Importing required classes import java.io.*; import java.util.*; import org.apache.commons.collections4.SetUtils; // Main class public class GFG { // Method 1 // To merge two Sets // using addAll() method public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two Sets to be merged // into the new Set and // returning the merged Set return SetUtils.union(a, b); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the Sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge two Sets System.out.println("Merged Set: " + mergeSet(a, b)); } }
Set a: [1, 3, 5, 7, 9] Set b: [0, 2, 4, 6, 8] Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Método 8: Usando Guayaba Iterables.concat()
Ilustración:
Input : a = [1, 3, 5, 7, 9] b = [0, 2, 4, 6, 8] Output : [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Ejemplo
Java
// Java Program to Demonstrate Merging of Two Sets // Using Guava Library // Importing required classes import com.google.common.collect.Iterables; import com.google.common.collect.Sets; import java.io.*; import java.util.*; // Main class public class GFG { // Method 1 // To merge two sets // using Guava Iterables.concat() public static <T> Set<T> mergeSet(Set<T> a, Set<T> b) { // Adding the two sets to be merged // into the new set and // returning the merged set return Sets.newHashSet(Iterables.concat(a, b)); } // Method 2 // Main driver method public static void main(String[] args) { // Creating the Sets to be merged // First set Set<Integer> a = new HashSet<Integer>(); a.addAll( Arrays.asList(new Integer[] { 1, 3, 5, 7, 9 })); // Second set Set<Integer> b = new HashSet<Integer>(); b.addAll( Arrays.asList(new Integer[] { 0, 2, 4, 6, 8 })); // Printing the above two Sets System.out.println("Set a: " + a); System.out.println("Set b: " + b); // Calling method 1 to merge two Sets System.out.println("Merged Set: " + mergeSet(a, b)); } }
Set a: [1, 3, 5, 7, 9] Set b: [0, 2, 4, 6, 8] Merged Set: [0, 1, 2, 3, 4, 5, 6, 7, 8, 9]
Nota: Cualquier elemento duplicado presentado en los conjuntos se descartará durante la fusión en todos los métodos anteriores.
Publicación traducida automáticamente
Artículo escrito por VipinKashyap y traducido por Barcelona Geeks. The original can be accessed here. Licence: CCBY-SA