Guava - Map

创建Map

通常在创建map时使用new HashMap<>();的方法,guava提供了一个简洁的方法

Maps.newHashMap();

List转换Map

        List<Solution> list= new ArrayList<>();
        //普通写法
        Map<Integer,Solution> map= Maps.newHashMap();
        for(Solution a:list){
            map.put(a.id,a);
        }

        //Maps.uniqueIndex(list, function);
        //guava的写法,注意: 此时list中的元素的属性不能有重复的,如果有的话会报错
        Map<Integer,Solution> map2 =Maps.uniqueIndex(list, new Function<Solution, Integer>() {
            @Override
            public Integer apply(Solution solution) {
                return solution.id;
            }
        });

一个key对应多个value的Multimap

在编写代码的过程中经常会用到

        Map<Integer,List<String>> maps= new HashMap<>();
        if(maps.get(1)==null){
            List<String> list= new ArrayList<>();
            list.add("1");
            maps.put(1,list);
        }else{
            maps.get(1).add("I");
        }

Guava的写法

//        ArrayListMultimap<Object, Object> objectObjectArrayListMultimap = ArrayListMultimap.create();
        HashMultimap<Integer, String> objectObjectHashMultimap = HashMultimap.create();
        //只需要put即可,不用判断是否为null情况
        objectObjectHashMultimap.put(1,"1");
        objectObjectHashMultimap.put(1,"2");
        objectObjectHashMultimap.put(1,"3");
        System.out.println(objectObjectHashMultimap.get(1));

ArrayListMultimap 返回的是一个List,HashMultimap返回的是一个Set

Multimap的实现

Implementation Keys 的行为类似 Values的行为类似
ArrayListMultimap HashMap ArrayList
HashMultimap HashMap HashSet
LinkedListMultiap LinkedHashMap LinkedList
LinkedHashMultimap LinkedHashMap LinkedHashSet
TreeMultimap TreeMap TreeSet
ImmutableListMultimap ImmutableMap ImmutableList
ImmutableSetMultimap ImmutableMap ImmutableSet

通过key找value 也可通过value找key的Map-BiMap

BiMap也可以反向把值映射到键,只要确保值唯一。

        BiMap<String,Integer> biMap= HashBiMap.create();
        biMap.put("I",1);
        biMap.put("V",5);
        biMap.put("X",10);
        biMap.put("L",50);
        biMap.put("C",100);
        biMap.put("D",500);
        biMap.put("M",1000);
        /*HashBiMap.create(new HashMap<String,Integer>(){{
            put("I",1);
            put("V",5);
            put("X",10);
            put("L",50);
            put("C",100);
            put("D",500);
            put("M",1000);
        }});*/
        BiMap<Integer, String> inverse = biMap.inverse();//翻转
        System.out.println(inverse);//{1=I, 5=V, 10=X, 50=L, 100=C, 500=D, 1000=M}
posted @ 2019-03-06 12:41  Hitechr  阅读(2592)  评论(0编辑  收藏  举报