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<Object>(set) - An
Object(input) to process - 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": addinputto the set. Return"Added successfully"if it was added, or"Element already exists"if it was already in the set."remove": removeinputfrom 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 containsinput(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
setisnull: return"Invalid set". - If
operationisnullor not one of the four above: return"Invalid operation". - For the
"find"operation, ifinputisnull: 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