The Wayback Machine - https://web.archive.org/web/20240914082626/https://www.geeksforgeeks.org/hashtable-foreach-method-in-java-with-examples/
Open In App

HashTable forEach() method in Java with Examples

Last Updated : 05 Jun, 2023
Summarize
Comments
Improve
Suggest changes
Like Article
Like
Save
Share
Report
News Follow

The forEach(BiConsumer) method of Hashtable class perform the BiConsumer operation on each entry of hashtable until all entries have been processed or the action throws an exception. 

The BiConsumer operation is a function operation of key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until all elements have been processed by the method or an exception occurs. Exceptions thrown by the Operation are passed to the caller. 

Syntax:

public void 
    forEach(BiConsumer<? super K, ? super V> action)

Parameters: This method takes a parameter name BiConsumer which represents the action to be performed for each element. 

Returns: This method returns nothing. 

Exception: This method throws:

  • NullPointerException: if the specified action is null.

Below programs illustrate the forEach(BiConsumer) method: 

Program 1: 

Java




// Java program to demonstrate
// forEach(BiConsumer) method.
 
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

Program 2: To Show NullPointerException 

Java




// Java program to demonstrate
// forEach(BiConsumer) method.
 
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

References: https://docs.oracle.com/javase/8/docs/api/java/util/Hashtable.html#forEach-java.util.function.BiConsumer-



Previous Article
Next Article

Similar Reads

foreach() loop vs Stream foreach() vs Parallel Stream foreach()
foreach() loopLambda operator is not used: foreach loop in Java doesn't use any lambda operations and thus operations can be applied on any value outside of the list that we are using for iteration in the foreach loop. The foreach loop is concerned over iterating the collection or array by storing each element of the list on a local variable and do
4 min read
Difference Between Collection.stream().forEach() and Collection.forEach() in Java
Collection.forEach() and Collection.stream().forEach() are used for iterating over the collections, there is no such major difference between the two, as both of them give the same result, though there are some differences in their internal working. Collection.stream().forEach() is basically used for iteration in a group of objects by converting a
3 min read
HashTable compute() method in Java with Examples
The compute(Key, BiFunction) method of Hashtable class allows to compute a mapping for the specified key and its current mapped value (or null if there is no current mapping is found). If the remapping function passed in compute() of Hashtable returns null as a return value then the mapping is removed from Hashtable(or remains absent if initially a
3 min read
Hashtable computeIfAbsent() method in Java with Examples
The computeIfAbsent(Key, Function) method of Hashtable class which allows you to compute value of a mapping for specified key if key is not already associated with a value (or is mapped to null). If mapping function of this method returns null, then no mapping is recorded. If the remapping function throws an exception, the exception is rethrown, an
2 min read
HashTable putIfAbsent() method in Java with Examples
The putIfAbsent(Key, value) method of Hashtable class which allows to map a value to a given key if given key is not associated with a value or mapped to null. A null value is returned if such key-value set is already present in the HashMap. Syntax: public V putIfAbsent(K key, V value) Parameters: This method accepts two parameters: key: specifies
2 min read
Hashtable keySet() Method in Java with Examples
The java.util.Hashtable is used to create a set of key elements in the hash table. It basically returns a set view of the keys, or we can create a new set and store the key elements in them. Syntax: public Set&lt;K&gt; keySet() K : type of the Keys in the hash table Parameters: The method does not take any parameter. Return Value: The method return
2 min read
Stream forEach() method in Java with examples
Stream forEach(Consumer action) performs an action for each element of the stream. Stream forEach(Consumer action) is a terminal operation i.e, it may traverse the stream to produce a result or a side-effect. Syntax : void forEach(Consumer&lt;? super T&gt; action) Where, Consumer is a functional interface and T is the type of stream elements. Note
2 min read
Iterable forEach() method in Java with Examples
It has been Quite a while since Java 8 released. With the release, they have improved some of the existing APIs and added few new features. One of them is forEach Method in java.lang.Iterable Interface. Whenever we need to traverse over a collection we have to create an Iterator to iterate over the collection and then we can have our business logic
3 min read
LinkedTransferQueue forEach() method in Java with Examples
The forEach() method of Java.util.concurrent.LinkedTransferQueue is an in-built function in Java which is used to traverse each element in this queue. Syntax: public void forEach(Consumer&lt;E&gt; action) Parameters: This method takes a parameter action which represents the action to be performed for each element. Return Value: This method does not
2 min read
LinkedBlockingDeque forEach() method in Java with Examples
The forEach() method of LinkedBlockingDeque performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Syntax: public void forEach(Consumer&lt;E&gt; action) Parameters: This method takes a parameter action which represents the action to be performed for each element. Return V
2 min read
CopyOnWriteArraySet forEach() method in Java with Examples
The forEach() method of CopyOnWriteArraySet is an in-built function in Java which is used to traverse each element in this Set. Syntax: public void forEach (Consumer&lt;E&gt; action) Parameters: This method takes a parameter action which represents the action to be performed for each element. Return Value: This method does not returns anything. Exc
2 min read
CopyOnWriteArrayList forEach() method in Java with Examples
The forEach() method of CopyOnWriteArrayList performs the given action for each element of the Iterable until all elements have been processed or the action throws an exception. Syntax: public void forEach (Consumer&lt;E&gt; action) Parameters: This method takes a parameter action which represents the action to be performed for each element. Return
2 min read
Properties forEach(BiConsumer) method in Java with Examples
The forEach(BiConsumer) method of Properties class perform the BiConsumer operation on each entry of hashtable until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until
2 min read
HashMap forEach(BiConsumer) method in Java with Examples
The forEach(BiConsumer) method of HashMap class perform the BiConsumer operation on each entry of hashmap until all entries have been processed or the action throws an exception. The BiConsumer operation is a function operation of the key-value pair of hashtable performed in the order of iteration. Method traverses each element of Hashtable until a
3 min read
Hashtable toString() Method in Java
The toString() method in the Hashtable class in Java returns a string representation of the key-value mappings contained in the hashtable. The string is in the form of a comma-separated list of key-value pairs enclosed in curly braces. The toString() method is inherited from the java.util.Hashtable class's parent class, java.util.Dictionary. Here's
2 min read
Hashtable elements() Method in Java
The elements() method in the Hashtable class in Java returns an enumeration of the values contained in the hashtable. The enumeration returned by this method traverses the hashtable's values in the order in which they were added to the hashtable. The elements() method is inherited from the java.util.Hashtable class's parent class, java.util.Diction
2 min read
Hashtable keys() Method in Java
As we all know enumeration defines java class type so do enumerations can have constructors, methods, and instance variables. The java.util.Hashtable.keys() method of Hashtable class in Java is used to get the enumeration of the keys present in the hashtable. Illustration: Syntax: public Enumeration&lt;K&gt; keys() Enumeration enu = Hash_table.keys
2 min read
Hashtable containsValue() Method in Java
The java.util.Hashtable.containsValue() method is used to check whether a particular value is being mapped by a single or more than one key in the Hashtable. It takes the Value as a parameter and returns True if that value is mapped by any of the keys in the table. Syntax: Hash_Table.containsValue(Object Value) Parameters: The method takes just one
2 min read
Hashtable containsKey() Method in Java
The java.util.Hashtable.containsKey() method is used to check whether a particular key is present in the Hashtable or not. It takes the key element as a parameter and returns True if that element is present in the table. Syntax: Hash_table.containsKey(key_element) Parameters: The method takes just one parameter key_element which refers to the key w
2 min read
Hashtable put() Method in Java
The java.util.Hashtable.put() method of Hashtable is used to insert a mapping into a table. This means we can insert a specific key and the value it is mapping to into a particular table. If an existing key is passed then the previous value gets replaced by the new value. If a new pair is passed, then the pair gets inserted as a whole. Syntax: Hash
3 min read
Hashtable get() Method in Java
The java.util.Hashtable.get() method of Hashtable class is used to retrieve or fetch the value mapped by a particular key mentioned in the parameter. It returns NULL when the table contains no such mapping for the key. Syntax: Hash_Table.get(Object key_element) Parameter: The method takes one parameter key_element of object type and refers to the k
2 min read
Hashtable isEmpty() Method in Java
The java.util.Hashtable.isEmpty() method of Hashtable class is used to check for the emptiness of the table. The method returns True if no key-value pair or mapping is present in the table else False. Syntax: Hash_Table.isEmpty() Parameters: The method does not take any parameters. Return Value: The method returns boolean true if the table is empty
2 min read
Hashtable size() Method in Java
The java.util.Hashtable.size() method of Hashtable class is used to get the size of the table which refers to the number of the key-value pair or mappings in the Table. Syntax: Hash_Table.size() Parameters: The method does not take any parameters. Return Value: The method returns the size of the table which also means the number of key-value pairs
2 min read
Hashtable remove() Method in Java
The java.util.Hashtable.remove() is an inbuilt method of Hashtable class and is used to remove the mapping of any particular key from the table. It basically removes the values for any particular key in the Table.Syntax: Hash_Table.remove(Object key) Parameters: The method takes one parameter key whose mapping is to be removed from the Table.Return
2 min read
Hashtable clone() Method in Java
The java.util.Hashtable.clone() method is used to return a shallow copy of the mentioned hash table. It just creates a copy of the table. Syntax: Hash_Table.clone() Parameters: The method does not take any parameters. Return Value: The method just returns a copy of the Hashtable. Below programs are used to illustrate the working of java.util.Hashta
2 min read
Hashtable clear() Method in Java
The java.util.Hashtable.clear() method in Java is used to clear and remove all of the keys from a specified Hashtable. Syntax: Hash_table.clear() Parameters: The method does not accept any parameters. Return Value: The method does not return any value. Below programs are used to illustrate the working of java.util.Hashtable.clear() Method: Program
2 min read
Hashtable contains() Method in Java
The java.util.Hashtable.contains(Object value) method in Java is used to check whether a particular value is being mapped by any keys present in the Hashtable. Syntax: Hash_table.contains(Object value) Parameters: The method accepts one parameter value of object type and refers to the value of the hashtable whose mapping is to be verified. Return V
2 min read
How HashTable Works Internally in Java?
Hashtable is a kind of Hash map but is synchronized. Hash map is non–synchronized, permits one null key &amp; multiple null values, not-thread safe i.e. cannot share between many threads without proper synchronization, the key/values pairs are stored in Hashtable. The Hash table does not allow null value/key. When using this you specify an object t
11 min read
Difference Between Hashtable and Synchronized Map in Java
The Hashtable class implements a hash table, which maps keys to values. Any non-null object can be used as a key or as a value. To successfully store and retrieve objects from a Hashtable, the objects used as keys must implement the hashCode method and also the equals method. Features of Hashtable: It is kind of like HashMap but is synchronized.Has
3 min read
Difference Between ConcurrentHashMap, HashTable and Synchronized Map in Java
Here we will be discussing out one by one individually then rolling onto the difference after having an adequate understanding of all three of them. We will be discussing ConcurrentHashMap first followed by HashTable, lastly followed by Synchronized Map. Let us start with ConcurrentHashMap first. The underlying data structure for ConcurrentHashMap
6 min read
Practice Tags :