Menu
Coddy logo textTech

Resumen - HashSet

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

challenge icon

Desafío

Fácil

Crea un método llamado processHashSet que reciba tres argumentos:

  1. Un HashSet de Objetos (set)
  2. Un Objeto (input) a procesar
  3. Un String (operation) que especifique la operación a realizar

El método debe realizar diferentes operaciones utilizando conceptos de Control de Flujo Avanzado:

Operaciones (usando Switch Expression):

  • "add": Agrega el input al set y devuelve un mensaje de éxito/error
  • "remove": Elimina el input del set y devuelve un mensaje de éxito/error
  • "find": Busca el input en el set utilizando sentencias de etiqueta (label statements)
  • "count": Cuenta los elementos de tipo Integer usando instanceof

Usa Guard Clauses para validar las entradas y manejar errores:

  • Si set es null: devuelve "Invalid set"
  • Si operation no es válida: devuelve "Invalid operation"
  • Para la operación "find" si input es null: devuelve "Cannot find null"

Pruébalo tú mismo

import java.util.HashSet;
import java.util.Scanner;
import java.util.Arrays;

public class Main {
    public static String processHashSet(HashSet<Object> set, Object input, String operation) {
        // Escribe tu código aquí
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Leer el conjunto inicial
        String[] items = scanner.nextLine().split(",");
        HashSet<Object> set = new HashSet<>();
        if (!items[0].equals("empty")) {
            for (String item : items) {
                // Intentar analizar como entero primero
                try {
                    set.add(Integer.parseInt(item));
                } catch (NumberFormatException e) {
                    set.add(item);
                }
            }
        }
        
        // Leer la entrada
        String inputStr = scanner.nextLine();
        Object input;
        try {
            input = Integer.parseInt(inputStr);
        } catch (NumberFormatException e) {
            input = inputStr;
        }
        
        // Leer la operación
        String operation = scanner.nextLine();
        
        System.out.println(processHashSet(set, input, operation));
    }
}

Todas las lecciones de Lógica y Flujo