HashMap的compute()方法,computeIfAbsent() 方法,computeIfPresent() 方法

566 阅读2分钟

这三个方法都是1.8以后新增的方法,其语法表示如下

hashmap.compute(K key,BiFunction remappingFunction)
如果key对应的value不存在则返回null,如果存在,返回通过remappingFunction重新计算后的值
hashmap.computeIfPresent(K key,BiFunction remappingFunction)
如果key对应的value不存在则返回null,如果存在,返回通过remappingFunction重新计算后的值
hashmap.computeIfAbsent(K key,BiFunction remappingFunction)
如果key对应的value不存在,则使用remappingFunction重新计算后的值,并保存为该 key的value,否则 返回 value.

image.png

  • compute()
     V oldValue = map.get(key);
     V newValue = remappingFunction.apply(key, oldValue);
     if (oldValue != null) {
        if (newValue != null)
           map.put(key, newValue);
        else
           map.remove(key);
     } else {
        if (newValue != null)
           map.put(key, newValue);
        else
           return null;
     }
     }

该方法使用上述代码块解释。

  • computeIfPresent()
     if (map.get(key) != null) {
         V oldValue = map.get(key);
         V newValue = remappingFunction.apply(key, oldValue);
         if (newValue != null)
             map.put(key, newValue);
         else
             map.remove(key);
     }
     }
  • computeIfAbsent()
     if (map.get(key) == null) {
         V newValue = mappingFunction.apply(key);
         if (newValue != null)
             map.put(key, newValue);
     }
     }

看到这里相信大家基本明白这三个方法的区别及使用场景,下面我们使用例子再来加深巩固一下:

public class Test {

	private static final String CHERRY = "cherry";
	private static final String BANANA = "banana";
	private static final String APPLE = "apple";
	private static final String ORANGE = "orange";

	/**
	 * @param args
	 */
	public static void main(String[] args) {
		Map<String, Double> prices = new HashMap<String, Double>(8);
		prices.put(APPLE, 8.5d);
		prices.put(BANANA, 9.3d);
		prices.put(ORANGE, 10.0d);

		// compute()语法为 hashmap.compute(K key,BiFunction remappingFunction)
		// 如果key对应的value不存在,则返回null,如果存在 ,返回通过remappingFunction重新计算后的值

		// 计算桔子打了10%折扣后的价格
		double price = prices.compute(ORANGE, (k, v) -> v - v * 10 / 100);
		System.out.println(price);
		// 如果不存在水果 cherry,直接返回空指针
		try {
			prices.compute(CHERRY, (k, v) -> v + v * 10 / 100);
		} catch (Exception ex) {
			ex.printStackTrace();
		}

		// computeIfPresent语法 为hashmap.computeIfPresent(K key,BiFunction
		// remappingFunction)
		// 如果key对应的value不存在,则返回null,如果存在,返回通过remappingFunction重新计算后的值

		// 计算桔子临时调整15%的价格
		price = prices.computeIfPresent(ORANGE, (k, v) -> v + v * 15 / 100);
		System.out.println("add 10%==" + price);

		// computeIfAbsent语法为 hashmap.computeIfAbsent(K key,BiFunction
		// remappingFunction ,如果key对应的value不存在,则使用remappingFunction重新计算后的值,
//		并保存为该 key的value,否则 返回 value.

		// 查询key为桔子是否存在,如果存在,直接返回价格
		price = prices.computeIfAbsent(ORANGE, v -> 18.8d);
		System.out.println("orange price == " + price);

		// 查询cherry价格
		price = prices.computeIfAbsent(CHERRY, v -> 41.8);
		System.out.println("cherry price == " + price);
	}

}

控制台输出内容如下:

9.0
java.lang.NullPointerException
	at test.Test.lambda$1(Test.java:32)
	at java.base/java.util.HashMap.compute(HashMap.java:1228)
	at test.Test.main(Test.java:32)
add 10%==10.35
orange price == 10.35
cherry price == 41.8