Removing an Element
Part of the Logic & Flow section of Coddy's Java journey — lesson 24 of 59.
The remove(element) method removes the specified element from the HashSet if it exists.
HashSet<String> fruits = new HashSet<>();
fruits.add("Apple");Remove "Apple" from the set
fruits.remove("Apple");After executing the above code, the set fruits contains:
[]Challenge
EasyCreate a method named <strong>removeElement</strong> that takes two arguments:
- A HashSet of Strings (
set) - A String (
element) to remove
The method should remove the specified element from the set and then print the updated set.
Try it yourself
import java.util.HashSet;
import java.util.Scanner;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
public class Main {
public static void removeElement(HashSet<String> set, String element) {
// Write your code here
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String setString = scanner.nextLine();
String element = scanner.nextLine();
Type setType = new TypeToken<HashSet<String>>(){}.getType();
HashSet<String> set = new Gson().fromJson(setString, setType);
removeElement(set, element);
}
}This lesson includes a short quiz. Start the lesson to answer it and track your progress.
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