Menu
Coddy logo textTech

Matemáticas - Intersección de HashSet

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

La intersección de dos conjuntos es un nuevo conjunto que contiene solo los elementos que están presentes en ambos conjuntos. En Java, puedes calcular la intersección utilizando el método retainAll().

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);

Este nuevo conjunto comenzará con todos los elementos del primer conjunto.

HashSet<Integer> intersectionSet = new HashSet<>(set1);

A continuación, mantén solo los elementos que también están en el segundo conjunto:
Usa el retainAll() método.

intersectionSet.retainAll(set2);
System.out.println("Intersection: " +
						intersectionSet);
// Output: [2]
challenge icon

Desafío

Fácil

Crea un método llamado <strong>intersectionSets</strong> que tome dos HashSets de enteros como entrada, calcule su intersección e imprímala en el formato:

Intersection: [2]

Hoja de referencia

La intersección de dos conjuntos contiene solo los elementos presentes en ambos conjuntos. Utilice retainAll() para calcular la intersección:

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

// Create new set with elements from first set
HashSet<Integer> intersectionSet = new HashSet<>(set1);

// Retain only elements that are also in second set
intersectionSet.retainAll(set2);
System.out.println("Intersection: " + intersectionSet);
// Output: [2]

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 intersectionSets(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 para el primer conjunto (p. ej., [1,2])
        String set1String = scanner.nextLine();
        // Leer cadena JSON para 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);
        
        intersectionSets(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