java8 map - 新特性常用方法

前言

java8中对map的使用新增了一些十分有用的方法,以下列举部分常用methed()

常用方法解析

1、compute()

参数格式:
compute(K key,BiFunction remappingFunction)

简要说明:
不在乎当前item的旧值,直接以remappingFunction()结果的新值为准,如果新值为空则移除当前item.

源码分析:

default V compute(K key,
            BiFunction remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        V oldValue = get(key);

        V newValue = remappingFunction.apply(key, oldValue);
        if (newValue == null) {
            // delete mapping
            if (oldValue != null || containsKey(key)) {
                // something to remove
                remove(key);
                return null;
            } else {
                // nothing to do. Leave things as they were.
                return null;
            }
        } else {
            // add or replace old mapping
            put(key, newValue);
            return newValue;
        }

使用格式:

testMap.compute("key1", (v1, v2) -> v2);

使用场景:
put()方法的增强使用

2、computeIfPresent()

参数格式:
computeIfPresent(K key, BiFunction remappingFunction)

简要说明:
计算item方法, 入参为item的key、remappingFunction
如果原来的key有值,且不为null,那么将remappingFunction中的新值给key,新值如果为空,移除当前key的item
如果原来key没值,直接给null

源码分析:

default V computeIfPresent(K key,
            BiFunction remappingFunction) {
        Objects.requireNonNull(remappingFunction);
        V oldValue;
        if ((oldValue = get(key)) != null) {
            V newValue = remappingFunction.apply(key, oldValue);
            if (newValue != null) {
                put(key, newValue);
                return newValue;
            } else {
                remove(key);
                return null;
            }
        } else {
            return null;
        }

使用格式:

testMap.computeIfPresent("key1", (v1, v2) -> "test");

使用场景:
put()方法的增强使用

3、computeIfAbsent()

参数格式: computeIfAbsent(K key, Function mappingFunction)

简要说明:
计算item方法,入参为item的key、remappingFunction
如果当前key旧值不为空,那么以旧值为准
如果当前key旧值为空,以function结果新值为准,新值为空则remove当前item

源码分析:

default V computeIfAbsent(K key,
            Function mappingFunction) {
        Objects.requireNonNull(mappingFunction);
        V v;
        if ((v = get(key)) == null) {
            V newValue;
            if ((newValue = mappingFunction.apply(key)) != null) {
                put(key, newValue);
                return newValue;
            }
        }

        return v;
    }

使用格式:

tempEntityRouteMap.computeIfAbsent(entityType, k -> TreeRangeMap.create());

使用场景:
put()方法的增强使用
未完待续......

你可能感兴趣的:(java8 map - 新特性常用方法)