Menu
Coddy logo textTech

Matematica - Unione di HashSet

Fa parte della sezione Logica e flusso del percorso Java di Coddy. Lezione 29 di 59.

L’unione di due insiemi è un nuovo insieme che contiene ogni elemento presente in uno dei due insiemi. In Java, puoi calcolare l’unione di due HashSets usando il metodo addAll(). Questo metodo aggiunge tutti gli elementi di un insieme a un altro (ignorando i duplicati).

Per prima cosa, crea due nuovi HashSet:

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

Usa il metodo addAll() per aggiungere gli elementi del secondo insieme al tuo insieme unione.

// Per prima cosa, crea un nuovo HashSet con set1
HashSet<Integer> unionSet = new HashSet<>(set1);
unionSet.addAll(set2); // Poi, aggiungi tutti gli elementi di set2
System.out.println("Union: " + unionSet);
// Output: [1, 2, 3] (l'ordine può variare)
challenge icon

Sfida

Facile

Crea un metodo chiamato <strong>unionSets</strong> che accetta in input due HashSet di interi, ne calcola l'unione e la stampa nel formato:

Union: [1, 2, 3]

Provalo tu

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) {
        // Scrivi qui il tuo codice
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Leggi la stringa JSON che rappresenta il primo insieme (ad es., [1,2])
        String set1String = scanner.nextLine();
        // Leggi la stringa JSON che rappresenta il secondo insieme (ad es., [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 iconMettiti alla prova

Questa lezione include un breve quiz. Inizia la lezione per rispondere e tenere traccia dei tuoi progressi.

Tutte le lezioni di Logica e flusso

Esercitati da solo: Compilatore Java online