guava:java:java.util.Map和java.util.Set的Key类型转换

昨天写了一博客《java:java.util.Map和java.util.Set的Key类型转换》,主要是想实现以java.util.MapKey类型转换,今天有空有研究了一下guava的代码,发现基于guava提供的API也是可以实现Key类型转换的:
关键就是Maps提供了uniqueIndex方法,可以将Map转换成Key不同的Map。

package net.gdface.facelog;

import static com.google.common.base.Preconditions.checkNotNull;
import java.util.Map;
import java.util.Map.Entry;
import java.util.Set;

import org.junit.Test;

import com.google.common.base.Function;
import com.google.common.collect.ImmutableMap;
import com.google.common.collect.ImmutableSet;
import com.google.common.collect.Iterators;
import com.google.common.collect.Maps;
import com.google.common.collect.Maps.EntryTransformer;

public class TestTransform {
    /** * convert {@code Map} to {@code Map} * @return {@linkplain ImmutableMap} */
    public static final Map transform(MapfromMap,final Functiontransformer){
        checkNotNull(fromMap,"fromMap is null");
        checkNotNull(transformer,"transformer is null");
        // 新的Map对象Key类型已经是K2了,只是Value类型成了Entry
        ImmutableMap> k2Entry = Maps.uniqueIndex(fromMap.entrySet(), new Function,K2>(){
            @Override
            public K2 apply(Entry input) {               
                return transformer.apply(input.getKey());
            }});
        // 再做一次转换将Entry转换成V,这个过程并没有创建新的Map,只是创建了k2Entry的代理对象
        Map k2V = Maps.transformEntries(k2Entry, new EntryTransformer,V>(){
            @Override
            public V transformEntry(K2 key, Entry value) {
                return value.getValue();
            }});
        return k2V;
    }
    /** * convert {@code Set} to {@code Set} * @return {@link ImmutableSet} */
    public static final Set transform(final SetfromSet,final Functiontransformer){
        checkNotNull(fromSet,"fromMap is null");
        checkNotNull(transformer,"transformer is null");
        return ImmutableSet.copyOf(Iterators.transform(fromSet.iterator(), transformer));
    }
    @Test
    public void test() {
        Map m1 = Maps.newLinkedHashMap();
        m1.put("1", "apple");
        m1.put("2", "orangle");
        m1.put("3", "banana");
        System.out.println(m1);
        Map m2 = transform(m1, new Function(){

            @Override
            public Integer apply(String input) {
                return Integer.valueOf(input);
            }});
        System.out.println(m2.toString());
    }

}

注意:
这个方法相比上篇博客中的方法要简单的多但是有区别的:
返回的Map对象是一个新的对象,与原Map对象没有任何关联,并且是不可变的(immutable)。
而上一篇博客中的方法返回的Map对象则是原对象的代理对象,并且是可变的(mutable),对新对象的任何操作实际都是对原对象的操作。

你可能感兴趣的:(java,guava,map,transform,key,java)