Populating and Accessing Map Data
Now that you know how to create a Java Map, let's explore how to populate and access the data stored within it.
Populating a Map
You can add key-value pairs to a Map using the put()
method. Here's an example:
Map<String, Integer> myMap = new HashMap<>();
myMap.put("apple", 5);
myMap.put("banana", 3);
myMap.put("cherry", 10);
In this example, we create a HashMap
and add three key-value pairs to it.
You can also use the putAll()
method to add multiple key-value pairs at once:
Map<String, Integer> anotherMap = new HashMap<>();
anotherMap.put("orange", 7);
anotherMap.put("grape", 12);
myMap.putAll(anotherMap);
This will add the key-value pairs from anotherMap
to myMap
.
Accessing Map Data
To retrieve the value associated with a specific key, you can use the get()
method:
int bananaCount = myMap.get("banana"); // Returns 3
If the key doesn't exist in the Map, the get()
method will return null
.
You can also check if a key exists in the Map using the containsKey()
method:
boolean hasApple = myMap.containsKey("apple"); // Returns true
boolean hasPear = myMap.containsKey("pear"); // Returns false
To iterate over the key-value pairs in a Map, you can use the keySet()
, values()
, or entrySet()
methods:
// Iterate over the keys
for (String key : myMap.keySet()) {
System.out.println("Key: " + key);
}
// Iterate over the values
for (int value : myMap.values()) {
System.out.println("Value: " + value);
}
// Iterate over the key-value pairs
for (Map.Entry<String, Integer> entry : myMap.entrySet()) {
System.out.println("Key: " + entry.getKey() + ", Value: " + entry.getValue());
}
By mastering the techniques covered in this tutorial, you'll be well on your way to effectively creating and using Java Maps in your applications.