Multiset
Multiset 虽然带了个set但是却允许重复元素,与set相同的是不保证元素顺序。
使用场景:获取文章中单词的出现次数
String[] wordArr = new String[]{"a","b","c","a","a","c","e"};
List<String> wordsList = Arrays.asList(wordArr);
Multiset<String> wordsMultiset = HashMultiset.create();
wordsMultiset.addAll(wordsList);
for(String key:wordsMultiset.elementSet()){
System.out.println(key+" count:"+wordsMultiset.count(key));
}
//e count:1
//b count:1
//c count:2
//a count:3
Multimap
Multiset 实现了类似 Map<K, List> 的数据结构
Multimap<String, Integer> multimap = ArrayListMultimap.create();
for (int i = 0; i < 10; i++) {
Random random = new Random();
multimap.put("1", random.nextInt());
}
System.out.println(multimap.size()); //10
System.out.println(multimap.keys()); //[1 x 10]
for (int i = 0; i < 5; i++) {
Random random = new Random();
multimap.put("2", random.nextInt());
}
System.out.println(multimap.size()); //15
System.out.println(multimap.keys()); //[2 x 5, 1 x 10]
for (String x : multimap.keySet()) {
System.out.println(x+" : ");
Map<String, Collection<Integer>> listMap = multimap.asMap();
Collection<Integer> collection = listMap.get(x);
for (Integer i : collection) {
System.out.println(i);
}
}
BiMap
BiMap提供了一种新的集合类型,它提供了key和value的双向关联的数据结构。 BiMap 要求Value是唯一的,Value重复会抛出错误
BiMap<Integer,String> bimap = HashBiMap.create();
bimap.put(1,"1");
bimap.put(2,"2");
bimap.put(3,"3");
bimap.put(2,null);
BiMap<String,Integer> valueMap = bimap.inverse();
System.out.println(valueMap.get("3")); //3
bimap.forcePut(4,"1"); //强制插入会覆盖重复Value的Key
System.out.println(valueMap.get("1")); //4
Table
Table 实现了类似Map<rowId, Map<columId, Value>> 及 可以 通过row 来查找也可以通过 colum来查找
Table<Integer, String,Integer> table = HashBasedTable.create();
table.put(1,"lilei",23);
table.put(2,"hanmeimei",24);
table.put(3,"lilei",3);
table.put(3,"lily",18);
Map<String, Integer> row = table.row(3);
System.out.println(row); //{lily=18, lilei=3}
Map<Integer, Integer> column = table.column("lilei");
System.out.println(column); //{1=23, 3=3}
RangeSet
RangeSet描述了一组不相连的、非空的区间。当把一个区间添加到可变的RangeSet时,所有相连的区间会被合并,空区间会被忽略。
RangeSet<Integer> rangeSet = TreeRangeSet.create();
rangeSet.add(Range.closed(1, 5));
System.out.println(rangeSet); //[[1‥5]]
rangeSet.add(Range.closedOpen(5, 10));
System.out.println(rangeSet); //[[1‥10)]
rangeSet.add(Range.closedOpen(8, 10));
System.out.println(rangeSet); //[[1‥10)]
rangeSet.add(Range.openClosed(10, 15));
System.out.println(rangeSet); //[[1‥10), (10‥15]]
rangeSet.remove(Range.open(8, 12));
System.out.println(rangeSet); //[[1‥8], [12‥15]]