forEach()
方法的语法是:
hashmap.forEach(BiConsumer<K, V> action)
这里,
hashmap 是
HashMap
类的对象。
forEach() 参数
forEach()
方法接受一个参数。
HashMap
的每个映射执行的操作
forEach() 返回值
forEach()
方法不返回任何值。
示例: Java HashMap forEach()
import java.util.HashMap; class Main { public static void main(String[] args) { // create a HashMap HashMap<String, Integer> prices = new HashMap<>(); // insert entries to the HashMap prices.put("Shoes", 200); prices.put("Bag", 300); prices.put("Pant", 150); System.out.println("Normal Price: " + prices); System.out.print("Discounted Price: "); // pass lambda expression to forEach() prices.forEach((key, value)-> { // decrease value by 10% value = value-value * 10/100; System.out.print(key + "=" + value + " "); }); } }
输出
Normal Price: {Pant=150, Bag=300, Shoes=200} Discounted Price: Pant=135 Bag=270 Shoes=180
在上面的例子中,我们创建了一个名为
prices 的哈希图。注意代码,
prices.forEach((key, value)-> { value = value-value * 10/100; System.out.print(key + "=" + value + " "); });
我们已将 lambda 表达式 作为参数传递给
forEach()
方法。在这里,
forEach()
方法为 hashmap 的每个条目执行由 lambda 表达式指定的操作
lambda 表达式将每个值减少 10% 并打印所有键和减少的值
要了解有关 lambda 表达式的更多信息,请访问 Java Lambda 表达式。
注意: forEach() 方法与 for-each 循环不同。我们可以使用 Java for-each 循环遍历哈希映射的每个条目。