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 theHashMap.
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 331002652Challenge
EasyCreate 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 valueTry 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));
}
}
}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