Menu
Coddy logo textTech

Declare a HashMap

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

Here's how you create a HashMap in Java:

HashMap<KeyType, ValueType> mapName = new HashMap<>();
  • KeyType: The data type of the keys.
  • ValueType: The data type of the values.
  • mapName: The name you give to the HashMap.

For example, to create a HashMap where keys are strings and values are integers, you would write:

HashMap<String, Integer> population = new HashMap<>();

This creates an empty HashMap named population that can store country names (strings) and their populations (integers).

To add values to the HashMap use the .put() method. For example:

population.put("USA", 331002651);
population.put("India", 1380004385);

Notice that the key is of type string and the value is of type integer.

If you try to add a duplicate key, the existing value will be overwritten. For example:

population.put("USA", 331002651); // Adds USA with population 331002651
population.put("USA", 331002652); // Updates USA's population to 331002652
challenge icon

Challenge

Easy

Create a method named createStringStringMap that takes no arguments and returns a HashMap where both keys and values are strings. The HashMap should contain the following key-value pairs:

  • Key: "apple", Value: "red"
  • Key: "banana", Value: "yellow"
  • Key: "grape", Value: “purple”

Cheat sheet

To create a HashMap in Java:

HashMap<KeyType, ValueType> mapName = new HashMap<>();

Example with String keys and Integer values:

HashMap<String, Integer> population = new HashMap<>();

To add values use the .put() method:

population.put("USA", 331002651);
population.put("India", 1380004385);

Adding a duplicate key overwrites the existing value:

population.put("USA", 331002651); // Adds USA
population.put("USA", 331002652); // Updates USA's value

Try it yourself

import java.util.HashMap;

public class Main {
    public static HashMap<String, String> createStringStringMap() {
        // Write your code here
    }

    public static void main(String[] args) {
        HashMap<String, String> map = createStringStringMap();
        
        // Print the HashMap
        for (String key : map.keySet()) {
            System.out.println(key + ": " + map.get(key));
        }
    }
}
quiz iconTest yourself

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

All lessons in Logic & Flow