1. Introduction

In Java, the Map interface provides several methods to find a specific key or value, such as containsKey(), containsValue(), and get(). This post demonstrates how to find a specific key and retrieve the associated value from a Map in Java.

2. Program Steps

1. Create and initialize a Map with some key-value pairs.

2. Print the original Map to the console.

3. Use the containsKey() method to check if the Map contains a specific key.

4. If the key is present, use the get() method to retrieve the value associated with the key.

5. Print the result of the search and the retrieved value to the console.

3. Code Program

import java.util.Map;
import java.util.HashMap;

public class FindInMap {

    public static void main(String[] args) {

        // Step 1: Create and initialize a Map with some key-value pairs
        Map<String, Integer> cityPopulation = new HashMap<>();
        cityPopulation.put("New York", 8419600);
        cityPopulation.put("Los Angeles", 3980400);
        cityPopulation.put("Chicago", 2716000);

        // Step 2: Print the original Map
        System.out.println("Original Map: " + cityPopulation);

        // Step 3: Use the containsKey() method to check if the Map contains a specific key
        String searchKey = "Chicago";
        boolean containsKey = cityPopulation.containsKey(searchKey);

        // Step 4: If the key is present, use the get() method to retrieve the value associated with the key
        if (containsKey) {
            Integer population = cityPopulation.get(searchKey);

            // Step 5: Print the result of the search and the retrieved value
            System.out.println("The population of " + searchKey + " is " + population);
        } else {
            System.out.println(searchKey + " is not present in the map.");
        }
    }
}

Output:

Original Map: {Chicago=2716000, New York=8419600, Los Angeles=3980400}
The population of Chicago is 2716000

4. Step By Step Explanation

Step 1: A Map named cityPopulation is created and initialized with some key-value pairs representing cities and their populations.

Step 2: The original Map, cityPopulation, is printed to the console.

Step 3: The containsKey() method is used to check if the Map cityPopulation contains the key "Chicago". The result is stored in a boolean variable containsKey.

Step 4: If the containsKey variable is true, the get() method is used to retrieve the value associated with the key "Chicago" and store it in an Integer variable population.

Step 5: The result of the search and the retrieved value population are printed to the console, showing The population of Chicago is 2716000 as "Chicago" is present in the original Map.