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
HashMap
class from thejava.util
package and creating a newMain
class. -
In the
main
method, we create a newHashMap
object calledpeople
that will holdString
keys andString
values. -
We use the
put
method to add three key-value pairs to thepeople
map. 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
get
method 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
size
method to print the number of key-value pairs in thepeople
map.
//Get all pairs
for (String x : people.keySet()) {
System.out.println("Pair: " + x + "->" + people.get(x));
}
- We use a
for
loop to iterate over all the keys in thepeople
map using thekeySet
method. For each key, we use theget
method to retrieve its associated value and print both to the console.
//Remove pair
people.remove("Idaho");
System.out.println(people);
- We use the
remove
method to remove the key-value pair with the key"Idaho"
from thepeople
map, and then print the updated map to the console.
//Clear all pairs
people.clear();
System.out.println(people);
}
}
- Finally, we use the
clear
method to remove all the key-value pairs from thepeople
map and then print the empty map to the console.
No comments:
Post a Comment