下面的例子实现了循环操作map里面的每个元素进行操作:
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 + " ");
});
}
}
以上实例中,我们将匿名函数 lambda 的表达式作为 forEach() 方法的参数传入,lambda 表达式将动态数组中的每个元素减少百分 10,然后输出结果。
下面的代码实现了:如果map中不存在"Shirt" 则操作
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("HashMap: " + prices);
// 计算 Shirt 的值
int shirtPrice = prices.computeIfAbsent("Shirt", key -> 280);
System.out.println("Price of Shirt: " + shirtPrice);
// 输出更新后的HashMap
System.out.println("Updated HashMap: " + prices);
}
}
以上代码执行结果为:
HashMap: {Pant=150, Bag=300, Shoes=180}
Price of Shoes: 180
Updated HashMap: {Pant=150, Bag=300, Shoes=180}
在以上实例中,我们创建了一个名为 prices 的 HashMap。
注意表达式:
prices.computeIfAbsent("Shirt", key -> 280)
代码中,我们使用了匿名函数 lambda 表达式 key-> 280 作为重新映射函数,prices.computeIfAbsent() 将 lambda 表达式返回的新值关联到 Shirt。
因为 Shirt 在 HashMap 中不存在,所以是新增了 key/value 对。
import java.util.HashMap;
class Main {
public static void main(String[] args) {
// 创建一个 HashMap
HashMap<String, Integer> prices = new HashMap<>();
// 往HashMap中添加映射关系
prices.put("Shoes", 180);
prices.put("Bag", 300);
prices.put("Pant", 150);
System.out.println("HashMap: " + prices);
// Shoes中的映射关系已经存在
// Shoes并没有计算新值
int shoePrice = prices.computeIfAbsent("Shoes", (key) -> 280);
System.out.println("Price of Shoes: " + shoePrice);
// 输出更新后的 HashMap
System.out.println("Updated HashMap: " + prices);
}
}
相反如果已经存在,如以上示例, Shoes 的映射关系在 HashMap 中已经存在,所以不会为 Shoes 计算新值
输出结果为:
HashMap: {Pant=150, Bag=300, Shoes=180}
Price of Shoes: 180
Updated HashMap: {Pant=150, Bag=300, Shoes=180}