Menu
Coddy logo textTech

Checking if an Element Exists

Part of the Logic & Flow section of Coddy's Java journey — lesson 25 of 59.

The contains(element) method checks whether the HashSet contains a specific element. It returns true if the element exists, and false otherwise.

This method runs in O(1) average time complexity, making it very efficient for lookups.

HashSet<String> fruits = new HashSet<>();
fruits.add("Banana");

Check if "Banana" exists in the set

boolean exists1 = fruits.contains("Banana");
// exists1 is true

Check if "Cherry" exists in the set

boolean exists2 = fruits.contains("Cherry");
// exists2 is false
challenge icon

Challenge

Easy

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

  1. A HashSet of Strings (set)
  2. A String (element) to check
    The method should print true if the element exists in the set, and false otherwise.

Cheat sheet

The contains(element) method checks whether a HashSet contains a specific element, returning true if found and false otherwise. It runs in O(1) average time complexity:

HashSet<String> fruits = new HashSet<>();
fruits.add("Banana");

boolean exists1 = fruits.contains("Banana");  // true
boolean exists2 = fruits.contains("Cherry");  // false

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 checkElement(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);
        
        checkElement(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