Menu
Coddy logo textTech

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 icon

Challenge

Easy

Create a method named <strong>removeElement</strong> that takes two arguments:

  1. A HashSet of Strings (set)
  2. 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);
    }
}
quiz iconTest yourself

This lesson includes a short quiz. Start the lesson to answer it and track your progress.

All lessons in Logic & Flow