java源码--Map

Map接口

  • 用于保存具有映射关系的数据结构,实现该接口的类可以通过键来获取对应的值。。
  • 可以将给定一个键值对存储在Map接口的实现类实例中,如:map.put("key", "value");
  • 当访问的值不存在的时候,会抛出NoSuchElementException异常
  • 当对象的类型和Map里元素类型不兼容时,会抛出ClassCastException异常
  • 当在不允许使用NULL对象的Map中使用NULL对象,会抛出NullPointerException异常
  • 当尝试修改一个只读的Map时,会抛出一个UnSupportedOperationException异常
  • 如果把Map里的所有key放在一起,就是一个Set集合

Map源码

package java.util;
import java.util.function.BiConsumer;
import java.util.function.BiFunction;
import java.util.function.Function;
import java.io.Serializable;

public interface Map<K,V> {
int size(); boolean isEmpty();//如果此映射不包含键-值映射关系,则返回 true。 boolean containsKey(Object key);//如果此映射包含指定键的映射关系,返回true boolean containsValue(Object value);//如果此映射将一个或多个键映射到指定值,返回true V get(Object key);//返回指定key所对应的value,如果此Map不包含该key,则返回null。 V put(K key, V value); V remove(Object key); void putAll(Map<? extends K, ? extends V> m); void clear(); //删除该Map对象中所有key-value对 Set<K> keySet(); //返回该Map中所有key所组成的Set集合。 Collection<V> values();//保存value的Collection集合 Set<Map.Entry<K, V>> entrySet();//返回Map中所包含的key-value对所组成的Set集合,每个集合元素都是Map.Entry(Entry是Map的内部类)对象。 interface Entry<K,V> {//Map内部的一个接口,Entry中封装着key和value K getKey();//返回该Entry里包含的key值。 V getValue();//返回该Entry里包含的value值。 V setValue(V value);//设置该Entry里包含的value值,并返回新设置的value值。 boolean equals(Object o); int hashCode(); public static <K extends Comparable<? super K>, V> Comparator<Map.Entry<K,V>> comparingByKey() { return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> c1.getKey().compareTo(c2.getKey()); } public static <K, V extends Comparable<? super V>> Comparator<Map.Entry<K,V>> comparingByValue() { return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> c1.getValue().compareTo(c2.getValue()); } public static <K, V> Comparator<Map.Entry<K, V>> comparingByKey(Comparator<? super K> cmp) { Objects.requireNonNull(cmp); return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> cmp.compare(c1.getKey(), c2.getKey()); } public static <K, V> Comparator<Map.Entry<K, V>> comparingByValue(Comparator<? super V> cmp) { Objects.requireNonNull(cmp); return (Comparator<Map.Entry<K, V>> & Serializable) (c1, c2) -> cmp.compare(c1.getValue(), c2.getValue()); } } boolean equals(Object o);//比较指定的对象与映射是否相等 int hashCode();//返回此映射的哈希码 }

 几个默认的方法

   //返回key键映射到的value值,如果此key不包含key的映射value值,则返回默认值defaultValue
    default V getOrDefault(Object key, V defaultValue) {
        V v;
        return (((v = get(key)) != null) || containsKey(key))
            ? v
            : defaultValue;
    }

    //遍历map中所有的内容
    default void forEach(BiConsumer<? super K, ? super V> action) {
        Objects.requireNonNull(action);
        for (Map.Entry<K, V> entry : entrySet()) {
            K k;
            V v;
            try {
                k = entry.getKey();
                v = entry.getValue();
            } catch(IllegalStateException ise) {
                // this usually means the entry is no longer in the map.
                throw new ConcurrentModificationException(ise);
            }
            action.accept(k, v);
        }
    }

    //将将所有的value替换为function.apply()函数处理后的值
    default void replaceAll(BiFunction<? super K, ? super V, ? extends V> function) {
        Objects.requireNonNull(function);
        for (Map.Entry<K, V> entry : entrySet()) {
            K k;
            V v;
            try {
                k = entry.getKey();
                v = entry.getValue();
            } catch(IllegalStateException ise) {
                // this usually means the entry is no longer in the map.
                throw new ConcurrentModificationException(ise);
            }

            // ise thrown from function is not a cme.
            v = function.apply(k, v);

            try {
                entry.setValue(v);
            } catch(IllegalStateException ise) {
                // this usually means the entry is no longer in the map.
                throw new ConcurrentModificationException(ise);
            }
        }
    }

    //判断value是否是key的映射值,如果不是将key的值设为value
    default V putIfAbsent(K key, V value) {
        V v = get(key);
        if (v == null) {
            v = put(key, value);
        }

        return v;
    }

    //判断value是否为key的映射值,是则删除
    default boolean remove(Object key, Object value) {
        Object curValue = get(key);
        if (!Objects.equals(curValue, value) ||
            (curValue == null && !containsKey(key))) {
            return false;
        }
        remove(key);
        return true;
    }

    //判断oldValue是否为key的映射值,是则将映射值替换为新的newValue值
    default boolean replace(K key, V oldValue, V newValue) {
        Object curValue = get(key);
        if (!Objects.equals(curValue, oldValue) ||
            (curValue == null && !containsKey(key))) {
            return false;
        }
        put(key, newValue);
        return true;
    }

    //判断key的映射值不为空,且key存在,则将key的映射值设为value 并返回
    default V replace(K key, V value) {
        V curValue;
        if (((curValue = get(key)) != null) || containsKey(key)) {
            curValue = put(key, value);
        }
        return curValue;
    }

    //如果指定的key键尚未与值value关联(或映射到{@code null}),则尝试使用给定的映射函数计算并将其输入到此映射中
    default V computeIfAbsent(K key,
            Function<? super K, ? extends V> 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;
    }

    //
    default V computeIfPresent(K key,
            BiFunction<? super K, ? super V, ? extends V> 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;
        }
    }

    //如果指定key键的value值存在且非空,则通过函数计算新newValue值,重新映射key的新值newValue。并返回
   //如果新值newValue为空,则删除此映射。 default V compute(K key, BiFunction<? super K, ? super V, ? extends V> 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; } } //如果key键对应的value值为空,则将value值映射到key上。否则,将映射值替换为映射函数的结果,如果结果是{@code null},则删除关联值。 default V merge(K key, V value, BiFunction<? super V, ? super V, ? extends V> remappingFunction) { Objects.requireNonNull(remappingFunction); Objects.requireNonNull(value); V oldValue = get(key); V newValue = (oldValue == null) ? value : remappingFunction.apply(oldValue, value); if(newValue == null) { remove(key); } else { put(key, newValue); } return newValue; }
原文地址:https://www.cnblogs.com/FondWang/p/11918516.html