Single Choice Easy

QCan the Java for-each loop be used to iterate over a Map collection?

ID: #23054 Enhanced For Loop (For-Each Loop) in Java 77 views
Question Info
#23054Q ID
EasyDifficulty
Enhanced For Loop (For-Each Loop) in JavaTopic

Choose the Best Option

Click any option to instantly check if you're correct.

  • A Yes, directly.
  • B No, only arrays are supported.
  • C Yes, but it must be done using the keySet() method.
  • D Yes, but it can only access keys, not values.
Correct Answer

Explanation

In Java, the for-each loop can indeed be used to iterate over a Map collection, but this must be done by utilizing methods such as keySet(), values(), or entrySet(). When using keySet(), the loop iterates over the keys of the map, allowing you to access the corresponding values through each key. The syntax would look like this: for (String key : map.keySet()) {}, where map is the instance of the Map. Alternatively, you can use for (Map.Entry entry : map.entrySet()) {} to directly access both keys and values. This versatility makes the for-each loop a powerful tool for working with maps, as it simplifies the process of retrieving elements compared to traditional iterations where you need to manage the index and look up values based on keys. Utilizing the for-each loop with maps promotes cleaner and more efficient code, ensuring that developers can effectively navigate through complex data structures without excessive boilerplate code.

Share This Question

Challenge a friend or share with your study group.