A HashMap is a data structure that is used to store key-value pairs. It is part of the java.util package and is implemented as a hash table. HashMaps are useful when you need to store and retrieve data based on keys rather than indexes, as in the case of arrays and ArrayLists.
In a HashMap, the keys must be unique, but the values can be duplicated.
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, String> people = new HashMap<String, String>();
people.put("Alabama", "Monica");
people.put("Arizona", "John");
people.put("Idaho", "Samantha");
//Get by Key - left side
System.out.println(people.get("Alabama"));
//Number of elements
System.out.println("Hash Size: " + people.size());
//Get all pairs
for (String x : people.keySet()) {
System.out.println("Pair: " + x + "->" + people.get(x));
}
//Remove pair
people.remove("Idaho");
System.out.println(people);
//Clear all pairs
people.clear();
System.out.println(people);
}
}
Explanation, block by block:
import java.util.HashMap;
public class Main {
public static void main(String[] args) {
HashMap<String, String> people = new HashMap<String, String>();
people.put("Alabama", "Monica");
people.put("Arizona", "John");
people.put("Idaho", "Samantha");
-
We start by importing the
HashMapclass from thejava.utilpackage and creating a newMainclass. -
In the
mainmethod, we create a newHashMapobject calledpeoplethat will holdStringkeys andStringvalues. -
We use the
putmethod to add three key-value pairs to thepeoplemap. The keys are U.S. state names and the values are people's names.
//Get by Key - left side
System.out.println(people.get("Alabama"));
- We use the
getmethod to retrieve the value associated with the key"Alabama"and print it to the console.
//Number of elements
System.out.println("Hash Size: " + people.size());
- We use the
sizemethod to print the number of key-value pairs in thepeoplemap.
//Get all pairs
for (String x : people.keySet()) {
System.out.println("Pair: " + x + "->" + people.get(x));
}
- We use a
forloop to iterate over all the keys in thepeoplemap using thekeySetmethod. For each key, we use thegetmethod to retrieve its associated value and print both to the console.
//Remove pair
people.remove("Idaho");
System.out.println(people);
- We use the
removemethod to remove the key-value pair with the key"Idaho"from thepeoplemap, and then print the updated map to the console.
//Clear all pairs
people.clear();
System.out.println(people);
}
}
- Finally, we use the
clearmethod to remove all the key-value pairs from thepeoplemap and then print the empty map to the console.