English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية

Java Basic Tutorial

Java Flow Control

Java Array

Java Object-Oriented (I)

Java Object-Oriented (II)

Java Object-Oriented (III)

Java Exception Handling

Java List

Java Queue (Queue)

Java Map Collection

Java Set Collection

Java Input/Output (I/O)

Java Reader/Writer

Java Other Topics

Java HashMap forEach() Usage and Example

Java HashMap Methods

Java HashMap forEach() method is used to perform a specified operation on each mapping of the hash map.

The syntax of forEach() method is:

hashmap.forEach(BiConsumer<K, V> action)

forEach() Parameters

  • action - Operation performed on each mapping of HashMap

forEach() Return Value

The forEach() method does not return any value.

Example: Java HashMap forEach()

import java.util.HashMap;
class Main {
  public static void main(String[] args) {
    // Creating HashMap
    HashMap<String, Integer> prices = new HashMap<>();
    //Inserting entries into HashMap
    prices.put("Shoes", 200);
    prices.put("Bag", 300);
    prices.put("Pant", 150);
    System.out.println("Market Price: "); + prices);
    System.out.print("Discount Price: ");
    // Pass the lambda expression to forEach()
    prices.forEach((key, value) -> {
      // Value Decrease10%
      value = value - value * 10/100;
      System.out.print(key + "=" + value + " ");
    });
  }
}

Output Result

Market Price: {Pant=150, Bag=300, Shoes=200}
Discount price: Pant=135 Bag=270 Shoes=180

In the above example, we created a hash map named prices. Note the code,

prices.forEach((key, value) -> {
  value = value - value * 10/100;
  System.out.print(key + "=" + value + " ");  
});

We have setLambda expressionpassed as a parameter to the forEach() method. Here,

  • The forEach() method executes the operation specified by the lambda expression for each entry of the hash table

  • Lambda expressions will reduce each value10%, and print all keys and reduced values

For more information about lambda expressions, please visitJava Lambda Expressions.

Note: forEach() method with for-each loop is different. We can useJava for-each loopTraverse each entry of the hash table.

Java HashMap Methods