Menu
Coddy logo textTech

Matematica - Differenza tra insiemi

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

La differenza tra due insiemi produce un nuovo insieme contenente gli elementi che si trovano nel primo insieme ma non nel secondo. In Java, puoi ottenerla usando il metodo removeAll().

First, create two HashSets.
HashSet<Integer> set1 = new HashSet<>();
set1.add(1);
set1.add(2);
set1.add(3);
HashSet<Integer> set2 = new HashSet<>();
set2.add(2);
set2.add(3);
set2.add(4);

Successivamente, crea un nuovo HashSet per la differenza: inizia con tutti gli elementi di set1:

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

Quindi, rimuovi tutti gli elementi che compaiono in set2:

differenceSet.removeAll(set2); // [1]
challenge icon

Sfida

Facile

Crea un metodo chiamato setDifference che accetti in input due HashSets di interi. Il metodo deve calcolare la differenza (gli elementi del primo insieme che non sono nel secondo) e stampare il risultato nel formato:

Difference: [elements]

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 setDifference(HashSet<Integer> set1, HashSet<Integer> set2) {
        // Scrivi il tuo codice qui
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Leggi la stringa JSON che rappresenta il primo insieme (ad esempio, [1,2,3])
        String set1String = scanner.nextLine();
        // Leggi la stringa JSON che rappresenta il secondo insieme (ad esempio, [2,3,4])
        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);

        setDifference(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