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<Object> (set)
  2. An Object (input) to process
  3. A String (operation) specifying the operation to perform

Using if/else statements and the HashSet methods you have already learned, the method should return a String based on operation:

  • "add": add input to the set. Return "Added successfully" if it was added, or "Element already exists" if it was already in the set.
  • "remove": remove input from the set. Return "Removed successfully" if it was removed, or "Element not found" if it was not in the set.
  • "find": return "Found at index: [index]" if the set contains input (where [index] is the position of the element in the iteration order), otherwise "Element not found".
  • "count": return "Number of integers: [count]", where [count] is the number of integers in the set.

Validate the inputs first:

  • If set is null: return "Invalid set".
  • If operation is null or not one of the four above: return "Invalid operation".
  • For the "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