In Java, you can use the forEach()
method from the Map
interface to iterate over the key-value pairs of a HashMap
.
Here's an example of how you can use the forEach()
method to iterate over a HashMap
:
import java.util.HashMap; import java.util.Map; public class Main { public static void main(String[] args) { // create a hash map Map<String, Integer> map = new HashMap<>(); // add key-value pairs to the map map.put("Apple", 1); map.put("Banana", 2); map.put("Orange", 3); // iterate over the map using the forEach method map.forEach((key, value) -> System.out.println(key + ": " + value)); } }Source:www.lautturi.com
This code creates a HashMap
called map
and adds three key-value pairs to it: "Apple" => 1, "Banana" => 2, and "Orange" => 3. It then uses the forEach()
method to iterate over the map and print the key-value pairs.
The forEach()
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. In this example, the BiConsumer
is defined as a lambda expression that takes two arguments: a key
and a value
, and prints them to the console.
For more information about HashMap
and other collections in Java, you can refer to the Java documentation (https://docs.oracle.com/javase/8/docs/api/java/util/HashMap.html).