To iterate over the keys and values in a Map
object in Java, you can use a for
loop in combination with the Map
object's entrySet()
method, which returns a Set
view of the mappings contained in the Map
.
Here's an example of how to do it:
import java.util.Map; import java.util.Set; public class Main { public static void main(String[] args) { Map<String, Integer> map = Map.of("a", 1, "b", 2, "c", 3); // Iterate over the entries in the map for (Map.Entry<String, Integer> entry : map.entrySet()) { String key = entry.getKey(); Integer value = entry.getValue(); System.out.println(key + ": " + value); } } }
This code creates a Map
object with three key-value pairs and then uses a for
loop to iterate over the entries in the map. The loop variable entry
is a Map.Entry
object that represents a single key-value pair in the map. The entrySet()
method returns a Set
view of the map's entries, which allows you to use the for-each
loop to iterate over the entries.
Inside the loop, the getKey()
and getValue()
methods of the Map.Entry
object are used to retrieve the key and value of the current entry.
You can use a similar approach to iterate over the keys or values in a Map
object, using the keySet()
or values()
methods instead of the entrySet()
method.