1. forEach方法
HashMap中的forEach()
方法用于对HashMap中的每个映射执行指定的操作。
forEach()
方法的语法为:
hashMap.forEach(BiConsumer<K, V> action)
注:hashMap是HashMap类的一个对象。
参数说明:
action
- 执行的操作
实例:
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: ");
//通过 lambda 表达式使用 forEach()
prices.forEach((key, value) -> {
// 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.forEach((key, value) -> {
// value 价格减少百分之 10
value = value - value * 10/100;
System.out.print(key + "=" + value + " ");
});
以上实例中,我们将匿名函数 lambda 的表达式作为forEach()
方法的参数传入,lambda 表达式将动态数组中的每个元素减少百分 10,然后输出结果。