java 8 中Map的computeIfAbsent,computeIfPresent,compute,merge 函数的使用
package com.test.com;
import java.util.HashMap;
import java.util.Map;
/**
* java 8 中Map的computeIfAbsent,computeIfPresent,compute,merge 函数的使用
*/
public class MapTest {
public static void main(String[] args) {
//computeIfAbsent() -- 不可以改变map中key对应的value值,map中不存在的可以加入
Map<String, Integer> mapCIAbsent = new HashMap<>();
//map中不存在key-value键值对,调用会加入到map
mapCIAbsent.computeIfAbsent("a", k -> 12);
System.out.println("mapCIAbsent--"+mapCIAbsent);
//map中对应key-value已存在,调用不会改变key对应的value值
mapCIAbsent.put("c", 13);
mapCIAbsent.computeIfAbsent("c", k -> 14);
System.out.println("mapCIAbsent--"+mapCIAbsent);
//computeIfPresent() -- 可以改变map中key对应的value值,map中不存在的不会加入
Map<String, Integer> mapCIPresent = new HashMap<>();
mapCIPresent.put("a", 12);
//map中对应key-value已存在,则使用 lambda 表达式生成新值并存储到 Map 中
mapCIPresent.computeIfPresent("a", (k, v) -> v - 1);
System.out.println("mapCIPresent--"+mapCIPresent);
//map中对应key-value不存在,则不执行任何操作,不会加入到map
mapCIPresent.computeIfPresent("b", (k, v) -> 13);
System.out.println("mapCIPresent--"+mapCIPresent); // 输出 false
//compute() -- 可以改变map中key对应的value值,map中不存在的可以加入
Map<String, Integer> mapCompute = new HashMap<>();
mapCompute.put("a", 12);
//map中对应key-value已存在,则使用 lambda 表达式生成新值并存储到 Map 中
mapCompute.compute("a", (k, v) -> v - 1);
System.out.println("mapCompute--"+mapCompute);
//map中对应key-value不存在,则使用 lambda 表达式生成新值并存储到 Map 中
mapCompute.compute("b", (k, v) -> 13);
System.out.println("mapCompute--"+mapCompute);
//merge() -- 原始值和要合并的新值,并返回合并后的值
Map<String, Integer> mapMerge = new HashMap<>();
mapMerge.put("a", 12);
// 合并键 "a" 的值,使用 lambda 表达式将原始值加上新值
mapMerge.merge("a", 8, (oldValue, newValue) -> oldValue + newValue);
System.out.println("mapMerge--"+mapMerge);
// 合并键 "b" 的值,由于键不存在于 map 中,直接存储新值
mapMerge.merge("b", 13, (oldValue, newValue) -> oldValue + newValue);
System.out.println("mapMerge--"+mapMerge);
}
}
测试结果
mapCIAbsent--{a=12}
mapCIAbsent--{a=12, c=13}
mapCIPresent--{a=11}
mapCIPresent--{a=11}
mapCompute--{a=11}
mapCompute--{a=11, b=13}
mapMerge--{a=20}
mapMerge--{a=20, b=13}