Sobes.tech
Junior — Middle

Is it possible to iterate directly over keys and values in a Map object?

sobes.tech AI

Answer from AI

Yes, in Java, you can directly iterate over the keys and values of a Map object using the entrySet() method. This method returns a set of key-value pairs, which is convenient to loop through.

Example:

Map<String, Integer> map = new HashMap<>();
map.put("apple", 3);
map.put("banana", 5);

for (Map.Entry<String, Integer> entry : map.entrySet()) {
    String key = entry.getKey();
    Integer value = entry.getValue();
    System.out.println(key + " = " + value);
}

Thus, you can get both the key and value on each iteration without additional searching.