Menu
Coddy logo textTech

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 false
challenge icon

Challenge

Easy

Create a method named keyChecker that takes two arguments:

  1. A HashMap named randomValues where keys are random strings and values are random values.
  2. An array keys representing 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 false

Try 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);
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow