Summary of Common Map Concepts
Summary of Common Map Concepts
entrySet(): This method returns a set of all the key-value pairs (entries) in a
map. Each entry is represented as an instance of Map.Entry.
Map.Entry: This is an interface that provides methods to access the key
(getKey()) and value (getValue()) of an entry.
Here's a simple example of how you can use entrySet() to loop over a HashMap and
access both the key and the value using Map.Entry.
java
Copy code
import java.util.*;
Explanation:
ageMap.entrySet() gives you all the key-value pairs (entries) in the map.
Map.Entry<String, Integer> allows you to access each entry's key and
value.
entry.getKey() gets the key (the name), and entry.getValue() gets the
value (the age).
2. Using getOrDefault()
getOrDefault(): This method is used to get the value for a key in the map. If
the key does not exist, it returns a default value that you specify.
Here's a simple example where we try to get values from a map using
getOrDefault().
java
Copy code
import java.util.*;
Explanation:
java
Copy code
import java.util.*;
Explanation:
This example demonstrates how to iterate over entries in a Map and access both the key and the
value.
java
Copy code
import java.util.*;
Explanation:
Map<String, Integer> ageMap = new HashMap<>(); creates a map where the keys
are String and values are Integer.
for (Map.Entry<String, Integer> entry : ageMap.entrySet()) iterates through
each entry in the map.
entry.getKey() and entry.getValue() retrieve the key and value of the current entry.
java
Copy code
import java.util.*;
Explanation: