Check If Key Exists
Part of the Logic & Flow section of Coddy's Java journey — lesson 13 of 59.
The containsKey(key) method checks if a specific key exists in a HashMap. It returns true or false.
For example let's populate a HashMap first:
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);And now we can check if a key exists:
boolean exists1 = scores.containsKey("Alice");
// exists1 is now true
boolean exists2 = scores.containsKey("Bob");
// exists2 is now falseChallenge
EasyCreate a method named keyChecker that takes two arguments:
- A
HashMapnamedrandomValueswhere keys are random strings and values are random values. - An array
keysrepresenting string keys.
The method should return the number of keys from the <strong>array</strong> that exist in the HashMap
Cheat sheet
The containsKey(key) method checks if a specific key exists in a HashMap and returns true or false:
HashMap<String, Integer> scores = new HashMap<>();
scores.put("Alice", 95);
boolean exists1 = scores.containsKey("Alice");
// exists1 is now true
boolean exists2 = scores.containsKey("Bob");
// exists2 is now falseTry it yourself
// --- Modules to convert string of hashmap to hashmap ---
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;
import java.lang.reflect.Type;
// -----------------------------
import java.util.HashMap;
import java.util.Scanner;
public class Main {
public static int keyChecker(HashMap<String, Integer> randomValues, String[] keys) {
// Write your code below
}
public static void main(String[] args) {
Scanner scanner = new Scanner(System.in);
String hashMapString = scanner.nextLine();
String arrayString = scanner.nextLine();
// Convert String of HashMap to HashMap
Type mapType = new TypeToken<HashMap<String, Integer>>(){}.getType();
HashMap<String, Integer> randomValues = new Gson().fromJson(hashMapString, mapType);
// Convert String of Array to Array
String[] keys = new Gson().fromJson(arrayString, String[].class);
int result = keyChecker(randomValues, keys);
System.out.println(result);
}
}
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 Arrays2HashMap Part 1
What is a HashMap?Declare a HashMapAccessing ValuesCheck If Key ExistsModifying DictionariesRecap - HashMap