The forEach(BiConsumer) method of the Hashtable class is used to perform a specified action on each key-value mapping in the hashtable. The action is represented by a BiConsumer, which receives the key and value of each entry.
- Hashtable does not allow null keys or null values.
- The order in which entries are processed is not guaranteed.
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// create a table and add some values
Map<String, Integer>
table = new Hashtable<>();
table.put("Pen", 10);
table.put("Book", 500);
table.put("Clothes", 400);
table.put("Mobile", 5000);
table.put("Booklet", 2500);
// add 100 in each value using forEach()
table.forEach((k, v) -> {
v = v + 100;
table.replace(k, v);
});
// print new mapping using forEach()
table.forEach(
(k, v) -> System.out.println("Key : " + k + ", Value : " + v));
}
}
Output
Key : Booklet, Value : 2600 Key : Clothes, Value : 500 Key : Mobile, Value : 5100 Key : Pen, Value : 110 Key : Book, Value : 600
Explanation: The first forEach() operation visits every key-value mapping. For each entry, the value is increased by 100, and replace() updates the corresponding value in the Hashtable.
Note: The output order of a
Hashtableis not guaranteed and may differ between executions.
Syntax
public void forEach(BiConsumer<? super K, ? super V> action)
- Parameters
: actionâ> a BiConsumer representing the operation to be performed for each key-value mapping. - Return Value: This method does not return any value.
- Exception
: NullPointerExceptionâ> thrown if the specifiedactionisnull.
Program: To Show NullPointerExceptionÂ
import java.util.*;
public class GFG {
// Main method
public static void main(String[] args)
{
// create a table and add some values
Map<Integer, String>
table = new Hashtable<>();
table.put(1, "100RS");
table.put(2, "500RS");
table.put(3, "1000RS");
try {
// add 100 in each value using forEach()
table.forEach((k, v) -> {
v = v + 100;
table.put(null, v);
});
}
catch (Exception e) {
System.out.println("Exception: " + e);
}
}
}
Output
Exception: java.lang.NullPointerException
Explanation: The forEach() method requires a valid BiConsumer action. Passing null as the action causes a NullPointerException.
Difference Between forEach() and entrySet() Loop
| Feature | forEach() | entrySet() Loop |
|---|---|---|
| Style | Uses lambda expression | Uses enhanced for loop |
| Code | Short and concise | More explicit |
| Key/Value | Directly available as parameters | Accessed using getKey() and getValue() |
| Control | No direct break or continue | Supports break and continue |
| Best For | Simple operations | Complex iteration logic |
Advantages of forEach()
- Provides short and concise code.
- Makes simple iteration easier to read.
- Works naturally with lambda expressions.
- Directly provides both key and value to the operation.
- Useful for performing the same operation on every entry.