Recap - HashSet
Part of the Logic & Flow section of Coddy's Java journey — lesson 28 of 59.
Challenge
EasyCreate a method named processHashSet that takes three arguments:
- A HashSet of Objects (
set) - An Object (
input) to process - 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
1Multi-dimensional Arrays
2D Arrays BasicsAccessing 2D Array ElementsNested Loops with 2D ArraysRecap - 2D ArraysMatrix Addition & SubstractionJagged Arrays3D Arrays And BeyondCommon 2D Array PatternsRecap - All About Arrays4HashSet Part 1
What is a HashSet?Adding an ElementRemoving an ElementChecking if an Element ExistsEmpty and SizeClear and CloneRecap - HashSet2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap