To iterate through a HashMap
in Java using a forEach
loop, you can use the forEach()
method of the Map
interface. This method takes a BiConsumer
as an argument, which is a functional interface that represents an operation that takes two input arguments and returns no result.
Here is an example of how to iterate through a HashMap
in Java using a forEach
loop:
HashMap<String, Integer> map = new HashMap<>(); map.put("A", 1); map.put("B", 2); map.put("C", 3); map.forEach((key, value) -> { System.out.println("Key: " + key + ", Value: " + value); });
In this example, the forEach()
method is called on the map
object, and a lambda expression is passed as an argument. The lambda expression takes two arguments, key
and value
, which represent the key and value of each entry in the HashMap
. The key and value are then printed to the console using the System.out.println()
method.
Note that the forEach()
method was introduced in Java 8, so it is not available in earlier versions of Java.
For more information on the forEach()
method and other ways to iterate through a HashMap
in Java, you can refer to the Java documentation or other online resources.