小白教程
所有教程
关于
Search
172.71.166.96
172.71.166.96
参数设置
贡献
退出
操作
编辑
移动
保护
信息
历史
删除
查看“Java hashmap computeifpresent”的源代码
本页内容
上一节:
Java_hashmap_computeifabsent
因为以下原因,您没有权限编辑本页:
您请求的操作仅限属于该用户组的用户执行:
用户
您可以查看和复制此页面的源代码。
{{DISPLAYTITLE:computeIfPresent()}}[[Category:java hashmap|22]] = Java HashMap computeIfPresent() 方法 = [[java hashmap|Java HashMap]] computeIfPresent() 方法对 hashMap 中指定 key 的值进行重新计算,前提是该 key 存在于 hashMap 中。 computeIfPresent() 方法的语法为: <pre> hashmap.computeIfPresent(K key, BiFunction remappingFunction) </pre> '''注:'''hashmap 是 HashMap 类的一个对象。 '''参数说明:''' * key - 键 * remappingFunction - 重新映射函数,用于重新计算值 === 返回值 === 如果 key 对应的 value 不存在,则返回该 null,如果存在,则返回通过 remappingFunction 重新计算后的值。 == 以下实例演示了 computeIfPresent() 方法的使用: <sample title="" desc="" lang="java" hererun="1"> 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); // 重新计算鞋加上10%的增值税后的价值 int shoesPrice = prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100); System.out.println("Price of Shoes after VAT: " + shoesPrice); // 输出更新后的HashMap System.out.println("Updated HashMap: " + prices); } } </sample> 执行以上程序输出结果为: <pre> HashMap: {Pant=150, Bag=300, Shoes=200} Price of Shoes after VAT: 220 Updated HashMap: {Pant=150, Bag=300, Shoes=220}} </pre> 在以上实例中,我们创建了一个名为 prices 的 HashMap。 注意表达式: <pre>prices.computeIfPresent("Shoes", (key, value) -> value + value * 10/100)</pre> 代码中,我们使用了匿名函数 lambda 表达式 (key, value) -> value + value * 10/100 作为重新映射函数。 要了解有关 lambda 表达式的更多信息,请访问 [https://www.xiaobai.wang/java/java8-lambda-expressions.html Java Lambda 表达式]。 [[java hashmap|Java HashMap]]
返回至“
Java hashmap computeifpresent
”。
上一节:
Java_hashmap_computeifabsent