English | 简体中文 | 繁體中文 | Русский язык | Français | Español | Português | Deutsch | 日本語 | 한국어 | Italiano | بالعربية
O método forEach() do Java HashMap é usado para executar uma operação específica em cada mapeamento do mapeamento de hash.
A sintaxe do método forEach() é:
hashmap.forEach(BiConsumer<K, V> ação)
ação - Ação executada em cada mapeamento do HashMap
O método forEach() não retorna nenhum valor.
import java.util.HashMap; class Main { public static void main(String[] args) { // Criar HashMap HashMap<String, Integer> prices = new HashMap<>(); //Inserir itens no HashMap prices.put("Shoes", 200); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("Preço de mercado: "); + prices); System.out.print("Preço com desconto: "); // Passar a expressão lambda para forEach() prices.forEach((key, value) -> { // valor diminui10% value = value - value * 10/100; System.out.print(key + "=" + value + " "); }); } }
Resultados de saída
Preço de mercado: {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 performs 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.