跳到主要内容

Java HashMap forEach() 方法

forEach() 方法的语法是:

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

这里的 hashmapHashMap 类的一个对象。

forEach() 参数

forEach() 方法接受单个参数。

  • action - 在 HashMap 的每个映射上执行的操作

forEach() 返回值

forEach() 方法不返回任何值。

示例:Java HashMap 的 forEach() 方法

import java.util.HashMap;

class Main {
public static void main(String[] args) {
// 创建一个 HashMap
HashMap<String, Integer> prices = new HashMap<>();

// 向 HashMap 插入条目
prices.put("Shoes", 200);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("Normal Price: " + prices);

System.out.print("Discounted Price: ");

// 向 forEach() 传递 lambda 表达式
prices.forEach((key, value) -> {

// 价格减少 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 的 hashmap。注意代码,

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 循环 来遍历 hashmap 的每个条目。