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 trueCheck if "Cherry" exists in the set
boolean exists2 = fruits.contains("Cherry");
// exists2 is falseChallenge
EasyCreate a method named <strong>checkElement</strong> that takes two arguments:
- A HashSet of Strings (
set) - A String (
element) to check
The method should printtrueif the element exists in the set, andfalseotherwise.
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"); // falseTry 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);
}
}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