forEach()
方法的语法是:
hashmap.forEach(BiConsumer<K, V> action)
forEach() 参数
forEach()
方法接受一个参数。
- action - 要对
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的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 Expressions。
注意:forEach()
方法与for-each循环不同。我们可以使用Java for-each循环来遍历hashmap的每个条目。
另请阅读