首页 > IT职业 > IT生活 > google guava集合之Multiset
Multiset看似是一个Set,但是实质上它不是一个Set,它没有继承Set接口,它继承的是Collection
它本质上是一个Set加一个元素计数器。
package cn.outofmemory.guava.collection; import com.google.common.base.Splitter; import com.google.common.collect.HashMultiset; import com.google.common.collect.Multiset; public class MultisetDemo { public static void main(String[] args) { Multiset multiset = HashMultiset.create(); String sentences = "this is a story, there is a good girl in the story."; Iterable words = Splitter.onPattern("[^a-z]{1,}").omitEmptyStrings().trimResults().split(sentences); for (String word : words) { multiset.add(word); } for (Object element : multiset.elementSet()) { System.out.println((String)element + ":" + multiset.count(element)); } } }
在上面的示例中我们对一段文字拆分成一个一个的单词,然后依次放入到multiset中,注意这段文字中有多个重复的单词,然后我们通过for循环遍历multiset中的每一个元素,并输出他们的计数。输出内容如下:
story:2 is:2 girl:1 there:1 a:2 good:1 the:1 in:1 this:1
显然计数不是问题,Multiset还提供了add和remove的重载方法,可以在add或这remove的同时指定计数的值。
常用实现 Multiset 接口的类有:
HashMultiset: 元素存放于 HashMap
LinkedHashMultiset: 元素存放于 LinkedHashMap,即元素的排列顺序由第一次放入的顺序决定
TreeMultiset:元素被排序存放于TreeMap
EnumMultiset: 元素必须是 enum 类型
ImmutableMultiset: 不可修改的 Mutiset
看到这里你可能已经发现 Guava Collections 都是以 create 或是 of 这样的静态方法来构造对象。这是因为这些集合类大多有多个参数的私有构造方法,由于参数数目很多,客户代码程序员使用起来就很不方便。而且以这种方式可以返回原类型的子类型对象。另外,对于创建范型对象来讲,这种方式更加简洁。
来自 “ ITPUB博客 ” ,链接:https://blog.itpub.net/1916/viewspace-2805663/ ,如需转载,请注明出处,否则将追究法律责任。