继续这次番石榴之旅,我们到达了Multiset 。 我可能不像Multimaps或Bimaps那样使用它,但是它确实有它的用途。
那么什么是多重集?
也许您可以猜到它是一个可以容纳同一对象的多个实例的集合。
这不仅仅是列表吗?
在Java中,列表和集合之间有两个基本区别。 列表可以保存同一对象的重复项,并且列表始终是有序的。 集合不能保存重复项,并且不能通过Set接口保证顺序。 (某些实现– LinkedHashSet,SortedSet等–当然可以提供有保证的顺序!)
因此,多集在列表和集之间占据了某种灰色区域。 允许重复,但不能保证订单。
这个集合有时也称为Bag ,实际上,这就是Apache Commons Collections称之为Mutlisets的东西。
那我要用什么呢?
关于多集的妙处在于,它们可以跟踪集合中每个特定对象的计数。 因此,您可以使用它们来计数东西。 您是否曾经编写过如下代码:
Map<MyClass,Integer> objectCounts = new HashMap<MyClass,Integer>();public void incrementCount(MyClass obj) {Integer count = objectCounts.get(obj);if (count == null) {objectCounts.put(obj,0);} else {objectCounts.put(obj,count++);}
}public int getCount(MyClass obj) {Integer count = objectCounts.get(obj);if (count == null) {return 0;} else {return count;}
}
有点笨拙? 让我们看看如何使用多集集:
Multiset<MyClass> myMultiset = HashMultiset.create();MyClass myObject = new MyClass();myMultiset.add(myObject);
myMultiset.add(myObject); // add it a second time.System.out.println(myMultiset.count(myObject)); // 2myMultiset.remove(myObject);
System.out.println(myMultiset.count(myObject)); // 1
如您所见,这要简单得多! 甚至可以一次添加/删除多个对象
Multiset<MyClass> myMultiset = HashMultiset.create();MyClass myObject = new MyClass();
myMultiset.add(myObject,5); // Add 5 copies of myObjectSystem.out.println(myMultiset.count(myObject)); // 5myMultiset.remove(myObject,2); // remove 2 copiesSystem.out.println(myMultiset.count(myObject)); // 3
很有用吗? 与往常一样,根据您的要求有几种可用的实现,我建议您看一下API: http : //docs.guava-libraries.googlecode.com/git-history/v9.0/javadoc/com/google/common /collect/Multiset.html
参考: Tom's编程博客博客中的JCG合作伙伴 Tom Jefferys提供的Google Guava Multisets 。
翻译自: https://www.javacodegeeks.com/2012/12/google-guava-multisets.html