Menu
Coddy logo textTech

Accessing Values

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

In a HashMap, each key is associated with a value. To access a value, you use the get() method and provide the key.

The HashMap then returns the value associated with that key. If the key doesn't exist in the HashMap, the get() method returns null.

Here's the basic syntax:

ValueType value = mapName.get(key);
  • mapName: The name of the HashMap.
  • key: The key whose associated value you want to retrieve.
  • ValueType: The data type of the value.

For example let's define the HashMap first:

HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);

And now to retrieve these values:

Integer aliceAge = ages.get("Alice");
// Alice's age: 30

Integer charlieAge = ages.get("Charlie");
// Charlie's age: null

In this example, we retrieve Alice's age using the key "Alice". Since "Charlie" is not a key in the HashMap, charlieAge is null.

challenge icon

Challenge

Easy

Create a method named getCapital that takes two arguments:

  1. A HashMap named capitals where keys are country names (strings) and values are capital city names (strings).
  2. A string country representing the name of a country.

The method should return the capital city of the given country by accessing the capitals HashMap. If the country is not found in the HashMap, return "Not found".

Cheat sheet

To retrieve a value from a HashMap, use the get() method with the key. If the key doesn't exist, it returns null.

ValueType value = mapName.get(key);

Example:

HashMap<String, Integer> ages = new HashMap<>();
ages.put("Alice", 30);
ages.put("Bob", 25);

Integer aliceAge = ages.get("Alice");  // 30
Integer charlieAge = ages.get("Charlie");  // null

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 String getCapital(HashMap<String, String> capitals, String country) {
        // Write your code below
    }

    public static void main(String[] args) {
        Scanner scanner = new Scanner(System.in);
        String hashMapString = scanner.nextLine();
        String country = scanner.nextLine();

        // Convert String of HashMap to HashMap
        Type mapType = new TypeToken<HashMap<String, String>>(){}.getType();
        HashMap<String, String> countryCapitals = new Gson().fromJson(hashMapString, mapType);

        String result = getCapital(countryCapitals, country);
        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