Menu
Coddy logo textTech

Recap - HashSet

Part of the Logic & Flow section of Coddy's Java journey — lesson 28 of 59.

challenge icon

Challenge

Easy

Create a method named processHashSet that takes three arguments:

  1. A HashSet of Objects (set)
  2. An Object (input) to process
  3. A String (operation) specifying the operation to perform

The method should perform different operations using concepts from Advanced Control Flow:

Operations (using Switch Expression):

  • "add": Add input to set and return success/failure message
  • "remove": Remove input from set and return success/failure message
  • "find": Search for input in set using label statements
  • "count": Count elements of type Integer using instanceof

Use Guard Clauses to validate inputs and Handle Errors:

  • If set is null: return "Invalid set"
  • If operation is invalid: return "Invalid operation"
  • For "find" operation if input is null: return "Cannot find null"

Try it yourself

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) {
        // Write your code here
    }
    
    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        
        // Read the initial set
        String[] items = scanner.nextLine().split(",");
        HashSet<Object> set = new HashSet<>();
        if (!items[0].equals("empty")) {
            for (String item : items) {
                // Try to parse as integer first
                try {
                    set.add(Integer.parseInt(item));
                } catch (NumberFormatException e) {
                    set.add(item);
                }
            }
        }
        
        // Read input
        String inputStr = scanner.nextLine();
        Object input;
        try {
            input = Integer.parseInt(inputStr);
        } catch (NumberFormatException e) {
            input = inputStr;
        }
        
        // Read operation
        String operation = scanner.nextLine();
        
        System.out.println(processHashSet(set, input, operation));
    }
}

All lessons in Logic & Flow