Guava源码解析十:Maps源码解析

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/dancheng1/article/details/85256412

构造方法

private Maps() {
}

私有的构造方法,可以看到这是一个真正的功能函数,下面对其函数进行分析

功能函数

返回一个不可变Map

1.ImmutableMap<K, V> immutableEnumMap(Map<K, ? extends V> map)

创建一个HashMap

1.HashMap<K, V> newHashMap()

2.HashMap<K, V> newHashMapWithExpectedSize(int expectedSize)

3.HashMap<K, V> newHashMap(Map<? extends K, ? extends V> map)

创建一个LinkedHashMap

1.LinkedHashMap<K, V> newLinkedHashMap()

2.LinkedHashMap<K, V> newLinkedHashMap(Map<? extends K, ? extends V> map)

创建一个ConcurrentMap

1.ConcurrentMap<K, V> newConcurrentMap()

创建一个TreeMap

1.TreeMap<K, V> newTreeMap()

2.TreeMap<K, V> newTreeMap(SortedMap<K, ? extends V> map)

3.TreeMap<K, V> newTreeMap(@Nullable Comparator<C> comparator)

创建一个EnumMap

1.EnumMap<K, V> newEnumMap(Class<K> type)

2.EnumMap<K, V> newEnumMap(Map<K, ? extends V> map)

创建一个IdentityHashMap

1.IdentityHashMap<K, V> newIdentityHashMap()

获取两个Map中不同元素的值

1.MapDifference<K, V> difference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right)

2.MapDifference<K, V> difference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence)

3.SortedMapDifference<K, V> difference(SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right)

根据函数和set,构造一个Map

1.Map<K, V> asMap(Set<K> set, Function<? super K, V> function)

2.SortedMap<K, V> asMap(SortedSet<K> set, Function<? super K, V> function)

3.NavigableMap<K, V> asMap(NavigableSet<K> set, Function<? super K, V> function)

根据函数和迭代器,构造一个不可变的Map

1.ImmutableMap<K, V> toMap(Iterator<K> keys, Function<? super K, V> valueFunction)

2.ImmutableMap<K, V> toMap(Iterator<K> keys, Function<? super K, V> valueFunction)

3. ImmutableMap<K, V> uniqueIndex(Iterable<V> values, Function<? super V, K> keyFunction)

4. ImmutableMap<K, V> uniqueIndex(Iterator<V> values, Function<? super V, K> keyFunction)

从配置文件中读取数据,创建一个不可变的Map

1.ImmutableMap<String, String> fromProperties(Properties properties)

返回一个Entry或一个Entry集合

1.Entry<K, V> immutableEntry(@Nullable K key, @Nullable V value)

2.Set<Entry<K, V>> unmodifiableEntrySet(Set<Entry<K, V>> entrySet)

3.Entry<K, V> unmodifiableEntry(final Entry<? extends K, ? extends V> entry)

返回一个特殊的BiMap类

1.BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap)

2.BiMap<K, V> unmodifiableBiMap(BiMap<? extends K, ? extends V> bimap)

根据一个Map和一个函数对Map进行转型

1.Map<K, V2> transformValues(Map<K, V1> fromMap, Function<? super V1, V2> function)

2.SortedMap<K, V2> transformValues(SortedMap<K, V1> fromMap, Function<? super V1, V2> function)

3.NavigableMap<K, V2> transformValues(NavigableMap<K, V1> fromMap, Function<? super V1, V2> function)

4.Map<K, V2> transformEntries(Map<K, V1> fromMap, Maps.EntryTransformer<? super K, ? super V1, V2> transformer)

5.SortedMap<K, V2> transformEntries(SortedMap<K, V1> fromMap, Maps.EntryTransformer<? super K, ? super V1, V2> transformer)

6.NavigableMap<K, V2> transformEntries(NavigableMap<K, V1> fromMap, Maps.EntryTransformer<? super K, ? super V1, V2> transformer)

自己写一个函数进行过滤Map,然后返回一个同类型的Map

分为4种过滤

一、针对Key进行过滤

1.Map<K, V> filterKeys(Map<K, V> unfiltered, Predicate<? super K> keyPredicate)

2.SortedMap<K, V> filterKeys(SortedMap<K, V> unfiltered, Predicate<? super K> keyPredicate)

3.NavigableMap<K, V> filterKeys(NavigableMap<K, V> unfiltered, Predicate<? super K> keyPredicate)

4.BiMap<K, V> filterKeys(BiMap<K, V> unfiltered, Predicate<? super K> keyPredicate)

二、针对Value进行过滤

1.Map<K, V> filterValues(Map<K, V> unfiltered, Predicate<? super V> valuePredicate)

2.SortedMap<K, V> filterValues(SortedMap<K, V> unfiltered, Predicate<? super V> valuePredicate)

3.NavigableMap<K, V> filterValues(NavigableMap<K, V> unfiltered, Predicate<? super V> valuePredicate)

4.BiMap<K, V> filterValues(BiMap<K, V> unfiltered, Predicate<? super V> valuePredicate)

三、针对Entry进行过滤

1.Map<K, V> filterEntries(Map<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate)

2.SortedMap<K, V> filterEntries(SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate)

3.SortedMap<K, V> filterSortedIgnoreNavigable(SortedMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate)

4.NavigableMap<K, V> filterEntries(NavigableMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate)

5.BiMap<K, V> filterEntries(BiMap<K, V> unfiltered, Predicate<? super Entry<K, V>> entryPredicate)

四、为含有过滤规则的Map进行过滤

1.Map<K, V> filterFiltered(Maps.AbstractFilteredMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate)

2.SortedMap<K, V> filterFiltered(Maps.FilteredEntrySortedMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate)

3.NavigableMap<K, V> filterFiltered(Maps.FilteredEntryNavigableMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate)

4.BiMap<K, V> filterFiltered(Maps.FilteredEntryBiMap<K, V> map, Predicate<? super Entry<K, V>> entryPredicate)

 

返回一个不可变Map

1.传入一个Map,返回一个不可变的Map容器

public static <K extends Enum<K>, V> ImmutableMap<K, V> immutableEnumMap(Map<K, ? extends V> map) {
    if(map instanceof ImmutableEnumMap) {
        //如果map为ImmutableEnumMap类型,直接强转为ImmutableEnumMap类型的容器
        ImmutableEnumMap i$1 = (ImmutableEnumMap)map;
        return i$1;
    } else if(map.isEmpty()) {
        //如果map为空,则直接返回新建的空的ImmutableMap容器
        return ImmutableMap.of();
    } else {
        Iterator i$ = map.entrySet().iterator();
        //在对map转型前,先判断其有没有属于null的key或value,如果有则直接抛出异常
        while(i$.hasNext()) {
            Entry entry = (Entry)i$.next();
            Preconditions.checkNotNull(entry.getKey());
            Preconditions.checkNotNull(entry.getValue());
        }
        //以上成立,则直接使用ImmutableEnumMap中函数为map进行转换
        return ImmutableEnumMap.asImmutable(new EnumMap(map));
    }
}

 

创建一个HashMap

1.直接返回一个新的HashMap

public static <K, V> HashMap<K, V> newHashMap() {
    return new HashMap();
}

2.返回一个想要长度的HashMap

public static <K, V> HashMap<K, V> newHashMapWithExpectedSize(int expectedSize) {
    return new HashMap(capacity(expectedSize));
}

根据传入的长度,返回一个实际可用expectedSize的HashMap,capacity方法就是计算实际长度的一个方法,下面看一下capacity方法的源码:

static int capacity(int expectedSize) {
    if(expectedSize < 3) {
        CollectPreconditions.checkNonnegative(expectedSize, "expectedSize");
        return expectedSize + 1;
    } else {
        return expectedSize < 1073741824?expectedSize + expectedSize / 3:2147483647;
    }
}

可以看到根据expectedSize < 1073741824?expectedSize + expectedSize / 3:2147483647;公式,实际返回的是3/4的expectedSize。为什么3/4这个系数呢,这就得和HashMap的负载因子有关了,它的系数默认为3/4,即存储长度为实际长度的3/4时,就进行扩容。而我们实际想要的是expectedSize的长度。真正用到他的3/4的时候就会扩容,影响存储效率,我们将他的值变为原来的3/4,我们用到expectedSize的时候就不会扩容了。

 

3.传入一个Map型变量,返回一个HashMap

public static <K, V> HashMap<K, V> newHashMap(Map<? extends K, ? extends V> map) {
    return new HashMap(map);
}

对于传入的Map赋值给新的HashMap步骤就由HashMap的putMapEntries方法进行操作了。

 

创建一个LinkedHashMap

1.直接返回一个新的LinkedHashMap

public static <K, V> LinkedHashMap<K, V> newLinkedHashMap() {
    return new LinkedHashMap();
}

2.传入一个Map变量,返回一个LinkedHashMap

public static <K, V> LinkedHashMap<K, V> newLinkedHashMap(Map<? extends K, ? extends V> map) {
    return new LinkedHashMap(map);
}

对于传入的Map赋值给新的LinkedHashMap步骤就由LinkedHashMap的putMapEntries方法进行操作了。

 

创建一个ConcurrentMap

1.直接返回一个新的ConcurrentMap

public static <K, V> ConcurrentMap<K, V> newConcurrentMap() {
    return (new MapMaker()).makeMap();
}

可以看到他的ConcurrentMap是由MapMaker类进行创建的,下面我们看一下MapMaker的makeMap方法:

public <K, V> ConcurrentMap<K, V> makeMap() {
    return (ConcurrentMap)(!this.useCustomMap?new ConcurrentHashMap(this.getInitialCapacity(), 0.75F, this.getConcurrencyLevel()):(ConcurrentMap)(this.nullRemovalCause == null?new MapMakerInternalMap(this):new MapMaker.NullConcurrentMap(this)));
}

查看源码,因为并没有对useCustomMap字段修改为true的操作,所以此方法最终实际执行的语句为:

return new ConcurrentHashMap(this.getInitialCapacity(), 0.75F, this.getConcurrencyLevel())

查看其中两个函数的源码:

int getInitialCapacity() {
    return this.initialCapacity == -1?16:this.initialCapacity;
}
int getConcurrencyLevel() {
    return this.concurrencyLevel == -1?4:this.concurrencyLevel;
}

与useCustomMap字段同理,initialCapacity和concurrencyLevel变量并没有被设置,所以返回了默认值,initialCapacity为16,concurrencyLevel为4。所以最后创建一个长度为16,负载因子为0.75,并发级别为4的concurrentMap。

 

创建一个TreeMap

1.直接返回一个新的TreeMap

public static <K extends Comparable, V> TreeMap<K, V> newTreeMap() {
    return new TreeMap();
}

2.传入一个Map变量,返回一个TreeMap,并将Map的值赋值给TreeMap

public static <K, V> TreeMap<K, V> newTreeMap(SortedMap<K, ? extends V> map) {
    return new TreeMap(map);
}

3.传入一个比较接口,返回一个根据传入的比较规则形成的TreeMap

public static <C, K extends C, V> TreeMap<K, V> newTreeMap(@Nullable Comparator<C> comparator) {
    return new TreeMap(comparator);
}

创建一个EnumMap

1.传入一个Class变量,返回一个EnumMap

public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Class<K> type) {
    return new EnumMap((Class)Preconditions.checkNotNull(type));
}

2.传入一个Map变量,返回一个EnumMap

public static <K extends Enum<K>, V> EnumMap<K, V> newEnumMap(Map<K, ? extends V> map) {
    return new EnumMap(map);
}

对于传入的Map赋值给新的EnumMap步骤就由EnumMap的putAll方法进行操作了。

 

创建一个IdentityHashMap

1.直接返回一个identityHashMap

public static <K, V> IdentityHashMap<K, V> newIdentityHashMap() {
    return new IdentityHashMap();
}

identityHashMap,与HashMap不同之处在于可以存入相同类的相同值,实际上他在put里的添加操作是不是使用equals而是用的==进行判断的

 

获取两个Map中不同元素的值

在说明Maps中这三个方法之前,我们先了解一下MapDifference接口和的实现类MapDifferenceImpl可以表现什么吧:

MapDifference接口:

public interface MapDifference<K, V> {
    boolean areEqual();
    Map<K, V> entriesOnlyOnLeft();
    Map<K, V> entriesOnlyOnRight();
    Map<K, V> entriesInCommon();
    Map<K, MapDifference.ValueDifference<V>> entriesDiffering();
    boolean equals(@Nullable Object var1);
    int hashCode();
    public interface ValueDifference<V> {
        V leftValue();
        V rightValue();
        boolean equals(@Nullable Object var1);
        int hashCode();
    }
}

它的实现类:

static class MapDifferenceImpl<K, V> implements MapDifference<K, V> {
    final Map<K, V> onlyOnLeft;
    final Map<K, V> onlyOnRight;
    final Map<K, V> onBoth;
    final Map<K, ValueDifference<V>> differences;

    MapDifferenceImpl(Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, ValueDifference<V>> differences) {
        this.onlyOnLeft = Maps.unmodifiableMap(onlyOnLeft);
        this.onlyOnRight = Maps.unmodifiableMap(onlyOnRight);
        this.onBoth = Maps.unmodifiableMap(onBoth);
        this.differences = Maps.unmodifiableMap(differences);
    }
    public boolean areEqual() {。。。}
    public Map<K, V> entriesOnlyOnLeft() {return this.onlyOnLeft; }
    public Map<K, V> entriesOnlyOnRight() {return this.onlyOnRight; }
    public Map<K, V> entriesInCommon() {return this.onBoth; }
    public Map<K, ValueDifference<V>> entriesDiffering() { return this.differences; }
    public boolean equals(Object object) {。。。}
    public int hashCode() {。。。}
    public String toString() {。。。}
}

可以看到MapDifferenceImpl实现类中有4个变量,根据字面意思便可以知道,onlyOnLeft只存变量名为left的Map中独有的;onlyOnRight只存变量名为right的Map中独有的;onBoth存储两个map中共有的key并且value也相等的元素;differences因为value存储的类型为ValueDifference,在查看MapDifference接口中ValueDifference类的结构,可以断定differences中存储的是共有的key并且value不同的元素

 

1.传入两个Map变量,根据left变量名的Map的类型进行判断是交给那个difference方法去处理

public static <K, V> MapDifference<K, V> difference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right) {
    if(left instanceof SortedMap) {
        SortedMap sortedLeft = (SortedMap)left;
        SortedMapDifference result = difference((SortedMap)sortedLeft, right);
        return result;
    } else {
        return difference(left, right, Equivalence.equals());
    }
}

2.传入两个Map,使用doDifference方法将两个Map中的元素进行分类

public static <K, V> MapDifference<K, V> difference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence) {
    Preconditions.checkNotNull(valueEquivalence);
    HashMap onlyOnLeft = newHashMap();
    HashMap onlyOnRight = new HashMap(right);
    HashMap onBoth = newHashMap();
    HashMap differences = newHashMap();
    doDifference(left, right, valueEquivalence, onlyOnLeft, onlyOnRight, onBoth, differences);
    return new Maps.MapDifferenceImpl(onlyOnLeft, onlyOnRight, onBoth, differences);
}

doDifference方法的源码:

private static <K, V> void doDifference(Map<? extends K, ? extends V> left, Map<? extends K, ? extends V> right, Equivalence<? super V> valueEquivalence, Map<K, V> onlyOnLeft, Map<K, V> onlyOnRight, Map<K, V> onBoth, Map<K, ValueDifference<V>> differences) {
    Iterator i$ = left.entrySet().iterator();
    //对left进行遍历操作
    while(i$.hasNext()) {
        Entry entry = (Entry)i$.next();
        Object leftKey = entry.getKey();
        Object leftValue = entry.getValue();
        //查看right中是否包括这个key值
        if(right.containsKey(leftKey)) {
            //如果right中也包括这个key值,则将这个值在right中去除
            Object rightValue = onlyOnRight.remove(leftKey);
            //判断这个key值的left和right的value值是否相等
            if(valueEquivalence.equivalent(leftValue, rightValue)) {
                //如果两个value值相等,将其填入onBoth的Map容器中
                onBoth.put(leftKey, leftValue);
            } else {
                //如果两个value值不相等,将其填入differences的Map容器中
                differences.put(leftKey, Maps.ValueDifferenceImpl.create(leftValue, rightValue));
            }
        } else {
            //如果这个key在right中不存在,则将其填入onlyOnLeft容器中
            onlyOnLeft.put(leftKey, leftValue);
        }
    }
}

3.传入一个SortedMap和一个Map变量,返回一个分类后的类

public static <K, V> SortedMapDifference<K, V> difference(SortedMap<K, ? extends V> left, Map<? extends K, ? extends V> right) {
    Preconditions.checkNotNull(left);
    Preconditions.checkNotNull(right);
    Comparator comparator = orNaturalOrder(left.comparator());
    TreeMap onlyOnLeft = newTreeMap((Comparator)comparator);
    TreeMap onlyOnRight = newTreeMap((Comparator)comparator);
    onlyOnRight.putAll(right);
    TreeMap onBoth = newTreeMap((Comparator)comparator);
    TreeMap differences = newTreeMap((Comparator)comparator);
    //根据以上的处理对两个Map中的元素进行分类处理
    doDifference(left, right, Equivalence.equals(), onlyOnLeft, onlyOnRight, onBoth, differences);
    return new Maps.SortedMapDifferenceImpl(onlyOnLeft, onlyOnRight, onBoth, differences);
}

根据函数和set,构造一个Map

此类函数实际上就是伪造了一个Map,虽说实现了Map接口,但是底层的数据结构完全不是Map的Entry结构。只不过是保存了一个Set为Key值,并且记录了一个规则,当想要取数据的时候,通过规则计算后才可以获取到数据,判断只需要判断Set集合中的元素便可。

1.传入一个set和一个规则,返回一个Map

public static <K, V> Map<K, V> asMap(Set<K> set, Function<? super K, V> function) {
    return (Map)(set instanceof SortedSet?asMap((SortedSet)((SortedSet)set), function):new Maps.AsMapView(set, function));
}

2.传入一个SortedSet和一个规则,返回一个SortMap

public static <K, V> SortedMap<K, V> asMap(SortedSet<K> set, Function<? super K, V> function) {
    return Platform.mapsAsMapSortedSet(set, function);
}

3.传入一个NavigableSet和一个规则,返回一个NavigableMap

public static <K, V> NavigableMap<K, V> asMap(NavigableSet<K> set, Function<? super K, V> function) {
    return new Maps.NavigableAsMapView(set, function);
}

根据函数和迭代器,构造一个不可变的Map

       此类方法传入的是一个容器的迭代器和一个规则,然后返回一个不可变的Map容器

1.传入一个key值容器和一个规则,直接交给重载函数去处理,返回一个不可变的Map容器

public static <K, V> ImmutableMap<K, V> toMap(Iterable<K> keys, Function<? super K, V> valueFunction) {
    return toMap((Iterator)keys.iterator(), valueFunction);
}

2.传入一个key值迭代器和一个规则返回一个不可变的map容器

public static <K, V> ImmutableMap<K, V> toMap(Iterator<K> keys, Function<? super K, V> valueFunction) {
    Preconditions.checkNotNull(valueFunction);
    LinkedHashMap builder = newLinkedHashMap();
    //使用迭代器中的值作为key值,使用规则计算出的值作为value值,存入builder中
    while(keys.hasNext()) {
        Object key = keys.next();
        builder.put(key, valueFunction.apply(key));
    }
    //返回一个不可变的容器
    return ImmutableMap.copyOf(builder);
}

3. 传入一个value值容器和一个规则,直接交给重载函数去处理,返回一个不可变的Map容器

public static <K, V> ImmutableMap<K, V> uniqueIndex(Iterable<V> values, Function<? super V, K> keyFunction) {
    return uniqueIndex((Iterator)values.iterator(), keyFunction);
}

4. 传入一个value值迭代器和一个规则返回一个不可变的map容器

public static <K, V> ImmutableMap<K, V> uniqueIndex(Iterator<V> values, Function<? super V, K> keyFunction) {
    Preconditions.checkNotNull(keyFunction);
    Builder builder = ImmutableMap.builder();
    //使用迭代器中的值作为value值,使用规则计算出的值作为key值,存入builder中
    while(values.hasNext()) {
        Object value = values.next();
        builder.put(keyFunction.apply(value), value);
    }
    //返回一个不可变的容器
    return builder.build();
}

 

从配置文件中读取数据,创建一个不可变的Map

1.从Properties获取的key和value,返回一个不可变的Map

public static ImmutableMap<String, String> fromProperties(Properties properties) {
    Builder builder = ImmutableMap.builder();
    Enumeration e = properties.propertyNames();
    //从properties获取的key和value,赋值到builder中
    while(e.hasMoreElements()) {
        String key = (String)e.nextElement();
        builder.put(key, properties.getProperty(key));
    }
    //返回一个不可变的Map
    return builder.build();
}

 

返回一个Entry或一个Entry集合

1.传入一个key和一个value,返回一个不可变的Entry

public static <K, V> Entry<K, V> immutableEntry(@Nullable K key, @Nullable V value) {
    return new ImmutableEntry(key, value);
}

 

返回一个特殊的BiMap类

1.传入一个BiMap返回一个线程安全的BiMap

guava中有一个Synchronized类,里面有很多guava中的集合的线程安全的类,详细可以看Synchronized类

public static <K, V> BiMap<K, V> synchronizedBiMap(BiMap<K, V> bimap) {
    return Synchronized.biMap(bimap, (Object)null);
}

2.传入一个BiMap返回一个unmodifiableBiMap

public static <K, V> BiMap<K, V> unmodifiableBiMap(BiMap<? extends K, ? extends V> bimap) {
    return new Maps.UnmodifiableBiMap(bimap, (BiMap)null);
}

根据一个Map和一个函数对Map进行转型

此类方法使用使用到了函数式编程,将一个Map的value作为新的Map的key,根据函数的规则计算出新的Map的Value,而这个转换只有在查看的时候才会做计算,而真正存储的是传入的map

1.传入一个Map和一个规则,返回一个有规则计算出来的Map

public static <K, V1, V2> Map<K, V2> transformValues(Map<K, V1> fromMap, Function<? super V1, V2> function) {
    return transformEntries((Map)fromMap, asEntryTransformer(function));
}

2.传入一个SortedMap和一个规则,返回一个由规则计算出来的新的Map

public static <K, V1, V2> SortedMap<K, V2> transformValues(SortedMap<K, V1> fromMap, Function<? super V1, V2> function) {
    return transformEntries((SortedMap)fromMap, asEntryTransformer(function));
}

3. 传入一个NavigableMap和一个规则,返回一个由规则计算出来的NavigableMap

public static <K, V1, V2> NavigableMap<K, V2> transformValues(NavigableMap<K, V1> fromMap, Function<? super V1, V2> function) {
    return transformEntries((NavigableMap)fromMap, asEntryTransformer(function));
}

4.传入一个Map和一个Maps规定的规则格式,根据规则返回一个新的Map

public static <K, V1, V2> Map<K, V2> transformEntries(Map<K, V1> fromMap, Maps.EntryTransformer<? super K, ? super V1, V2> transformer) {
    return (Map)(fromMap instanceof SortedMap?transformEntries((SortedMap)((SortedMap)fromMap), transformer):new Maps.TransformedEntriesMap(fromMap, transformer));
}

5.传入一个NavigableMap和一个Maps规定的规则格式,根据规则返回一个新的NavigableMap

public static <K, V1, V2> NavigableMap<K, V2> transformEntries(NavigableMap<K, V1> fromMap, Maps.EntryTransformer<? super K, ? super V1, V2> transformer) {
    return new Maps.TransformedEntriesNavigableMap(fromMap, transformer);
}

自己写一个函数进行过滤Map,然后返回一个同类型的Map

一、针对Key进行过滤

使用keyPredicate函数接口制定过滤规则,对Map进行过滤,对于Map中Key进行过滤的类FilteredKeyMap源码如下:

private static class FilteredKeyMap<K, V> extends Maps.AbstractFilteredMap<K, V> {
    Predicate<? super K> keyPredicate;
    FilteredKeyMap(Map<K, V> unfiltered, Predicate<? super K> keyPredicate, Predicate<? super Entry<K, V>> entryPredicate) {
        super(unfiltered, entryPredicate);
        this.keyPredicate = keyPredicate;
    }
    protected Set<Entry<K, V>> createEntrySet() {
        return Sets.filter(this.unfiltered.entrySet(), this.predicate);
    }

    Set<K> createKeySet() {
        return Sets.filter(this.unfiltered.keySet(), this.keyPredicate);
    }

    public boolean containsKey(Object key) {
        return this.unfiltered.containsKey(key) && this.keyPredicate.apply(key);
    }
}

可以看到他的方法中对KeySet进行了过滤处理,使用了Set中的filter方法

 

1.传入一个Map和过滤他的规则,返回一个新的Map

public static <K, V> Map<K, V> filterKeys(Map<K, V> unfiltered, Predicate<? super K> keyPredicate) {
    if(unfiltered instanceof SortedMap) {
        //如果这个Map属于SortedMap,则交给其他的重载方法进行处理
        return filterKeys((SortedMap)((SortedMap)unfiltered), keyPredicate);
    } else if(unfiltered instanceof BiMap) {
        //如果这个Map属于BiMap,则交给其他重载方法进行处理
        return filterKeys((BiMap)((BiMap)unfiltered), keyPredicate);
    } else {
        Preconditions.checkNotNull(keyPredicate);
        Predicate entryPredicate = keyPredicateOnEntries(keyPredicate);
        return (Map)(unfiltered instanceof Maps.AbstractFilteredMap?filterFiltered((Maps.AbstractFilteredMap)((Maps.AbstractFilteredMap)unfiltered), entryPredicate):new Maps.FilteredKeyMap((Map)Preconditions.checkNotNull(unfiltered), keyPredicate, entryPredicate));
    }
}

2.传入一个SortedMap,然后交给filterEntries方法进行处理

public static <K, V> SortedMap<K, V> filterKeys(SortedMap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
    return filterEntries((SortedMap)unfiltered, keyPredicateOnEntries(keyPredicate));
}

3. 传入一个NavigableMap,然后交给filterEntries方法进行处理

public static <K, V> NavigableMap<K, V> filterKeys(NavigableMap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
    return filterEntries((NavigableMap)unfiltered, keyPredicateOnEntries(keyPredicate));
}

4. 传入一个BiMap,然后交给filterEntries方法进行处理

public static <K, V> BiMap<K, V> filterKeys(BiMap<K, V> unfiltered, Predicate<? super K> keyPredicate) {
    Preconditions.checkNotNull(keyPredicate);
    return filterEntries((BiMap)unfiltered, keyPredicateOnEntries(keyPredicate));
}

Maps还提供了一些对Value、Entry、含有过滤器的Map进行过滤的方法。与上面过滤key的方法大体一样,都是继承了AbstractFilteredMap抽象类,实现了各自的过滤功能

猜你喜欢

转载自blog.csdn.net/dancheng1/article/details/85256412
今日推荐