Google Guava—集合篇

853 阅读1分钟

1.双向Set:MultiSet[ 无序可重复Set ]

        String str = "this a cat and that is a mice where is the food";
        String[] strs = str.split(" ");
        //把字符串放进Multiset里面
        Multiset<String> set=HashMultiset.create();
        for(String temp:strs){
            set.add(temp);
        }
        //获取Multiset里的元素
        Set<String> eset=set.elementSet();
        for(String temp:eset){
            System.out.println(temp+"---------->"+set.count(temp));//count记录出现的次数
        }

2.双向map:BiMap[ key ,value都不能重复的map ]

JDK提供的map可以根据key找到value,而BiMap可以根据value找到key。

在创建biMap的时候内部维护2个map,

BiMap biMap = HashBiMap.create();
biMap.put("id", "01");
System.out.println(biMap.get("id"));// 01
System.out.println(biMap.inverse().get("01"));// id
//biMap.inverse().inverse() == biMap()

3.一对多Map:MultiMap[ key可以重复的map ]

multiMap.get("brand") // 返回类型为:Collection
Multimap<Object, Object> multiMap = ArrayListMultimap.create();
multiMap.put("brand","apple");
multiMap.put("brand","sony");
multiMap.put("brand","google");
System.out.println(multiMap.get("brand")); // [apple, sony, google]

4.多个key:Table

需要保存所有学生多门课程成绩:Map<String, Map<String, Integer>> map = new ..

table.row() // 返回类型为: map

table.rowKeySet() // 返回类型:Set 

Table<String,String,Integer> table = HashBasedTable.create();
table.put("张三","语文",93);
table.put("张三","数学",100);
table.put("张三","英语",99);

table.put("李四","语文",98);
table.put("李四","数学",90);
table.put("李四","英语",89);
System.out.println(table.row("李四"));       // {语文=98, 数学=90, 英语=89}
System.out.println(table.get("张三","英语")); // 99
System.out.println(table.get("张三","体育")); // null