Menu
Coddy logo textTech

Mat. - Interseção de HashSet

Parte da seção Lógica e Fluxo do Journey de Java da Coddy — lição 30 de 59.

A interseção de dois conjuntos é um novo conjunto que contém apenas os elementos presentes em ambos os conjuntos. Em Java, você pode calcular a interseção usando o método retainAll().

Primeiro, crie dois novos HashSets:

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

Este novo conjunto começará com todos os elementos do primeiro conjunto.

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

Em seguida, retenha apenas os elementos que também estão no segundo conjunto:
Use o método retainAll().

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

Desafio

Fácil

Crie um método chamado <strong>intersectionSets</strong> que recebe dois HashSets de inteiros como entrada, calcula a interseção deles e imprime no formato:

Intersection: [2]

Folha de consulta

A interseção de dois conjuntos contém apenas elementos presentes em ambos os conjuntos. Use retainAll() para calcular a interseção:

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]

Experimente você mesmo

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) {
        // Escreva seu código aqui
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        // Leia a string JSON para o primeiro conjunto (ex.: [1,2])
        String set1String = scanner.nextLine();
        // Leia a string JSON para o segundo conjunto (ex.: [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 iconTeste seus conhecimentos

Esta lição inclui um quiz rápido. Comece a lição para respondê-lo e acompanhar seu progresso.

Todas as lições de Lógica e Fluxo