Skip to content
geeksforgeeks
  • Tutorials
    • Python
    • Java
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
    • Practice Coding Problems
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Java Arrays
  • Java Strings
  • Java OOPs
  • Java Collection
  • Java 8 Tutorial
  • Java Multithreading
  • Java Exception Handling
  • Java Programs
  • Java Project
  • Java Collections Interview
  • Java Interview Questions
  • Java MCQs
  • Spring
  • Spring MVC
  • Spring Boot
  • Hibernate
Open In App
Next Article:
Hashtable computeIfAbsent() method in Java with Examples
Next article icon

HashTable forEach() method in Java with Examples

Last Updated : 05 Jun, 2023
Comments
Improve
Suggest changes
Like Article
Like
Report

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-


Next Article
Hashtable computeIfAbsent() method in Java with Examples

A

AmanSingh2210
Improve
Article Tags :
  • Java
  • java-basics
  • Java-Functions
  • Java-HashTable
Practice Tags :
  • Java

Similar Reads

    Hashtable in Java
    Hashtable class, introduced as part of the Java Collections framework, implements a hash table that 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 an
    12 min read
    HashTable forEach() method in Java with Examples
    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.
    2 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
    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: T
    2 min read
    Java Hashtable put() Method
    The Hashtable.put() method is a part of java.util package. This method is used to insert a mapping into a table. This means we can insert a specific key and the value it maps to into a particular table. If an existing key is passed, then the previous value gets replaced by the new value. If a new pa
    2 min read
    Java Hashtable get() Method
    The Hashtable.get() method is a built-in method of the java.util.Hashtable class. This method 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. In this article, we will learn about the Ha
    3 min read
    Java Hashtable isEmpty() Method
    The Hashtable.isEmpty() method is a built-in method of the java.util.Hashtable class. This method is used to check if the table is empty or not. The method returns true, if no key-value pair or mapping is present in the table, else it returns false.Syntax of Hashtable isEmpty() Methodhash_table.isEm
    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 tab
    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 wh
    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
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences