guava入门学习2(新集合)
新集合类型
这可能是你梦寐以求的集合,在解决瘙痒方面,功能异常强大
2.1 MultiSet
痛点:统计次数
传统做法:
Map<String,Integer> count = new HashMap<String,Integer>();
guava实现:
Multiset multiset = HashMultiset.create();
multiset.add("c”);
multiset.add("c”);
multiset.count(“c”);
2.2 MultiMap
痛点:单个指标对应集合
传统做法:
Map<String,List<String>>、Map<String,Set<String>>
guava实现:
Multimap<String, String> multimap = ArrayListMultimap.create();
multimap.put("a","a1");
multimap.put("a","a2");
List<String> a = (List)multimap.get("a");
a.forEach(System.out::print);
2.3 BiMap
痛点:一对一键值对关系维护
传统做法:
Map<String,Integer> nameMap = new HashMap<String,Integer>();
Map<Integer,String> idMap = new HashMap<Integer,String>();
需要同步维护两个map
guava实现:
BiMap<String,Integer> biMap = HashBiMap.create();
biMap.put("aa",1);
biMap.put("bb",2);
biMap.put("cc",3);
Integer id = biMap.get("aa");
System.out.println(id);
String name = biMap.inverse().get(2);
System.out.println(name);
2.4 Table
痛点:需要模拟行列的关系,复杂度及代码维护代价提高
传统做法:
Map<String,Map<String,String>> tabMap = new HashMap<String,Map<String,String>>();
字段间的关系不清晰,可读性大,维护难度大
guava实现:
Table<String,String,String> table = HashBasedTable.create();
table.put("line1","coll1","l1c1");
table.put("line1","coll2","l1c2");
table.put("line2","coll1","l2c1");
Map<String,String> row1Map = table.row("line1");
Map<String,String> coll1Map = table.column("coll1");
posted on 2017-11-19 13:14 听风tingfeng 阅读(144) 评论(0) 编辑 收藏 举报