Menu
Coddy logo textTech

Matemáticas - Unión de HashSets

Parte de la sección Lógica y Flujo del Journey de Java de Coddy — lección 29 de 59.

La unión de dos conjuntos es un nuevo conjunto que contiene todos los elementos que están en cualquiera de los conjuntos. En Java, puedes calcular la unión de dos HashSets usando el método addAll(). Este método agrega todos los elementos de un conjunto a otro (ignorando duplicados).

Primero, crea dos nuevos HashSets:

HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);

Usa el método addAll() para agregar elementos del segundo conjunto a tu conjunto unión.

// First, create a new HashSet with set1
HashSet<Integer> unionSet = new HashSet<>(set1);
unionSet.addAll(set2); // Then, add all elements from set2
System.out.println("Union: " + unionSet);
// Output: [1, 2, 3] (order may vary)
challenge icon

Desafío

Fácil

Crea un método llamado <strong>unionSets</strong> que toma dos HashSets de enteros como entrada, calcula su unión e imprime en el formato:

Union: [1, 2, 3]

Hoja de referencia

La unión de dos conjuntos contiene todos los elementos que están en cualquiera de los conjuntos. Utilice addAll() para calcular la unión de dos HashSets:

HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);

// Crear la unión copiando el primer conjunto y agregando todos los elementos del segundo
HashSet<Integer> unionSet = new HashSet<>(set1);
unionSet.addAll(set2);
System.out.println("Union: " + unionSet);
// Salida: [1, 2, 3] (el orden puede variar)

Pruébalo tú mismo

import java.util.HashSet;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;

public class Main {
    public static void unionSets(HashSet<Integer> set1, HashSet<Integer> set2) {
        // Escribe tu código aquí
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Leer cadena JSON que representa el primer conjunto (p. ej., [1,2])
        String set1String = scanner.nextLine();
        // Leer cadena JSON que representa el segundo conjunto (p. ej., [2,3])
        String set2String = scanner.nextLine();

        Type setType = new TypeToken<HashSet<Integer>>(){}.getType();
        HashSet<Integer> set1 = new Gson().fromJson(set1String, setType);
        HashSet<Integer> set2 = new Gson().fromJson(set2String, setType);
        
        unionSets(set1, set2);
    }
}
quiz iconPonte a prueba

Esta lección incluye un breve cuestionario. Empieza la lección para responderlo y registrar tu progreso.

Todas las lecciones de Lógica y Flujo