Java Hashtable - forEach() Method
The java.util.Hashtable.forEach() method is used to perform the given action for each entry in this map until all entries have been processed or the action throws an exception.
Syntax
public void forEach(BiConsumer<? super K,? super V> action)
Here, K and V are the type of key and value respectively maintained by the container.
Parameters
action |
Specify the action to be performed for each entry. |
Return Value
void type.
Exception
NA.
Example:
In the example below, the java.util.Hashtable.forEach() method is used to perform the given action for each entry in the given hashtable.
import java.util.*; import java.util.function.BiConsumer; public class MyClass { public static void main(String[] args) { //creating a hashtable Hashtable<Integer, String> Htable = new Hashtable<Integer, String>(); //populating hashtable Htable.put(101, "John"); Htable.put(102, "Marry"); Htable.put(103, "Kim"); Htable.put(104, "Jo"); Htable.put(105, "Sam"); //creating an action BiConsumer<Integer, String> action = new MyAction(); //using forEach method Htable.forEach(action); } } // Defining action in MyAction class class MyAction implements BiConsumer<Integer, String> { public void accept(Integer k, String v) { System.out.println("Key = " + k + ", Value = " + v); } }
The output of the above code will be:
Key = 101, Value = John Key = 102, Value = Marry Key = 103, Value = Kim Key = 104, Value = Jo Key = 105, Value = Sam
❮ Java.util - Hashtable