In the ArrayList section, you discovered that Arrays organize elements in a specific order, accessed through integer indices. In contrast, HashMaps store elements as pairs of keys and values, enabling access using keys of various types (such as strings) rather than just integers.
An object serves as a key to retrieve another object, functioning as its value. HashMaps can accommodate various types, such as pairs of String keys and Integer values, or uniform types like String keys and String values.
Instantiate a HashMap named capitalCities to store pairs of String keys and String values.
import HashMap<String, String> |
The HashMap
class has many useful methods. For example, to add items to it, use the put()
method:
// Import the HashMap class public class Main { // Add keys and values (Country, City)
|
To access a value in the HashMap
, use the get()
method and refer to its key:
|
To remove an item, use the remove()
method and refer to the key:
|
To remove all items, use the clear()
method:
capitalCities.clear(); |
To find out how many items there are, use the size()
method:
|
Iterate through the elements of a HashMap using a for-each loop.
Reminder: Utilize the keySet() method to obtain only the keys, and employ the values() method if you solely require the values.
// Print keys |
// Print values |
// Print keys and values |
Keys and values within a HashMap are object instances. In the preceding examples, we utilized objects of the “String” type. It’s important to note that in Java, a String is an object, not a primitive type. When using other types like int, you should specify a corresponding wrapper class, such as Integer. For other primitive types, utilize Boolean for boolean, Character for char, Double for double, etc.
Instantiate a HashMap named people to store pairs of String keys and Integer values.
// Import the HashMap class import java.util.HashMap;
public class Main { public static void main(String[] args) {
// Create a HashMap object called people HashMap<String, Integer> people = new HashMap<String, Integer>();
// Add keys and values (Name, Age) people.put(“John”, 32); people.put(“Steve”, 30); people.put(“Angie”, 33);
for (String i : people.keySet()) { System.out.println(“key: “ + i + ” value: “ + people.get(i)); } } } |