标签:bim values asm family value get entry int 排序
guava所提供的这些真正意义来讲不属于Map
1.Multimap:key重复,但是value返回数组
业务场景:封装成Map后,要对某一个key进行分组平铺
Multimap<String,String> multimap = HashMultimap.create(); multimap.put("xxx","aaa"); multimap.put("xxx","bbb"); multimap.put("xxx","ccc"); Collection<String> values = multimap.get("xxx"); System.out.println(values);
运行结果:[aaa, ccc, bbb]
2. ListMultimap、ArrayListMultimap
:同上,只是加了泛型(Collection 转成 LIST)
ListMultimap<String,String> listMultimap = ArrayListMultimap.create(); listMultimap.put("xxx","aaa"); listMultimap.put("xxx","bbb"); listMultimap.put("xxx","ccc"); List<String> strings = listMultimap.get("xxx"); System.out.println(strings);
ArrayListMultimap<Integer,Object> listMap = ArrayListMultimap.create(); listMap.put(1, "hello"); listMap.put(3, "test"); listMap.put(1, "guava"); listMap.put(2, "stydy"); System.out.println(listMap.get(1));
运行结果:[aaa, ccc, bbb]
3.SetMultimap:与上面类似,List转Set
SetMultimap<String,String> setMultimap = HashMultimap.create(); setMultimap.put("xxx","aaa"); setMultimap.put("xxx","vvv"); setMultimap.put("xxx","sss"); setMultimap.put("xxx","aaa"); Set<String> sets = setMultimap.get("xxx"); System.out.println(sets);
运行结果:[aaa, vvv, sss]
4.asMap()方法:将上述对象的Key进行hash排序
// 返回的数据结构为:集合中存放集合,按照1,2,3自然顺序排序 Multimap<Integer, Object> multimap = ArrayListMultimap.create(); multimap.put(1, "hello"); multimap.put(3, "test"); multimap.put(1, "guava"); multimap.put(2, "stydy"); System.out.println(multimap.asMap()); for (Map.Entry<Integer, Object> entry : multimap.entries()){ Integer key = entry.getKey(); Object value = entry.getValue(); System.out.println(key + " " + value); }
运行结果:
{1=[hello, guava], 2=[stydy], 3=[test]}
1 hello
1 guava
2 stydy
3 test
5..count(key) 查看key重复数量
Multiset<Integer> mset = HashMultiset.create(); mset.add(3); mset.add(1); mset.add(1); mset.add(2); System.out.println(mset.count(1)); System.out.println(mset); for(Integer i: mset){ System.out.print(i); }
运行结果:2 [1 x 2, 2, 3] 1123
6.BiMap:双向的map,可以通过key查value(key同map会覆盖),也可以通过value查key(value不能重复,不然会报错)
BiMap<String,Integer> biMap = HashBiMap.create(); biMap.put("hezhong1",1); biMap.put("hezhong1",55); biMap.put("hezhong2",2); //biMap.put("xxx",2);//2重复会报错 biMap.put("hezhong3",3); System.out.println(biMap.get("hezhong1")); System.out.println(biMap.inverse().get(2));
返回结果:
55
hezhong2
关于guava的HashMultiset、ListMultimap、Multiset、SetMultimap、ArrayListMultimap、BiMap、HashBiMap使用
标签:bim values asm family value get entry int 排序
原文地址:https://www.cnblogs.com/charkey/p/14601814.html