本文整理了Java中com.google.common.collect.Multiset
类的一些代码示例,展示了Multiset
类的具体用法。这些代码示例主要来源于Github
/Stackoverflow
/Maven
等平台,是从一些精选项目中提取出来的代码,具有较强的参考意义,能在一定程度帮忙到你。Multiset
类的具体详情如下:
包路径:com.google.common.collect.Multiset
类名称:Multiset
[英]A collection that supports order-independent equality, like Set, but may have duplicate elements. A multiset is also sometimes called a bag.
Elements of a multiset that are equal to one another are referred to as occurrences of the same single element. The total number of occurrences of an element in a multiset is called the count of that element (the terms "frequency" and "multiplicity" are equivalent, but not used in this API). Since the count of an element is represented as an int, a multiset may never contain more than Integer#MAX_VALUEoccurrences of any one element.
Multiset refines the specifications of several methods from Collection. It also defines an additional query operation, #count, which returns the count of an element. There are five new bulk-modification operations, for example #add(Object,int), to add or remove multiple occurrences of an element at once, or to set the count of an element to a specific value. These modification operations are optional, but implementations which support the standard collection operations #add(Object) or #remove(Object) are encouraged to implement the related methods as well. Finally, two collection views are provided: #elementSet contains the distinct elements of the multiset "with duplicates collapsed", and #entrySet is similar but contains Entry instances, each providing both a distinct element and the count of that element.
In addition to these required methods, implementations of Multiset are expected to provide two static creation methods: create(), returning an empty multiset, and create(Iterable), returning a multiset containing the given initial elements. This is simply a refinement of Collection's constructor recommendations, reflecting the new developments of Java 5.
As with other collection types, the modification operations are optional, and should throw UnsupportedOperationException when they are not implemented. Most implementations should support either all add operations or none of them, all removal operations or none of them, and if and only if all of these are supported, the setCount methods as well.
A multiset uses Object#equals to determine whether two instances should be considered "the same," unless specified otherwise by the implementation.
Common implementations include ImmutableMultiset, HashMultiset, and ConcurrentHashMultiset.
If your values may be zero, negative, or outside the range of an int, you may wish to use com.google.common.util.concurrent.AtomicLongMapinstead. Note, however, that unlike Multiset, AtomicLongMapdoes not automatically remove zeros.
See the Guava User Guide article on Multiset.
[中]支持顺序独立相等的集合,如Set,但可能有重复的元素。多集有时也称为包。
多个集合中彼此相等的元素称为同一单个元素的引用。一个元素在多个集合中出现的总数称为该元素的计数(术语“频率”和“多重性”是等效的,但在本API中不使用)。由于一个元素的计数用int表示,因此一个多集可能包含的任何一个元素的出现次数不得超过整数#MAX_值。
Multiset从集合中细化了几种方法的规范。它还定义了一个额外的查询操作#count,它返回元素的计数。有五个新的批量修改操作,例如#add(Object,int),一次添加或删除元素的多个引用,或者将元素的计数设置为特定值。这些修改操作是可选的,但是支持标准收集操作的实现#add(Object)或#remove(Object)也被鼓励实现相关的方法。最后,提供了两个集合视图:#elementSet包含multiset的不同元素“重复项已折叠”,而#entrySet类似,但包含条目实例,每个实例同时提供一个不同的元素和该元素的计数。
除了这些必需的方法之外,Multiset的实现还需要提供两种静态创建方法:create(),返回一个空Multiset;create(Iterable),返回一个包含给定初始元素的Multiset。这只是对集合的构造函数建议的改进,反映了Java5的新发展。
与其他集合类型一样,修改操作是可选的,在未实现时应引发UnsupportedOperationException。大多数实现应该支持全部添加操作或全部不支持,全部删除操作或全部不支持,如果且仅当所有这些操作都支持时,setCount方法也应该支持。
除非实现中另有规定,否则multiset使用Object#equals确定两个实例是否应被视为“相同”。
常见的实现包括ImmutableMultiset、HashMultiset和ConcurrentHashMultiset。
如果您的值可能为零、负或超出int的范围,您可能希望使用com。谷歌。常见的util。同时发生的原子龙马平头。但是,请注意,与Multiset不同,AtomicLongMap不会自动删除零。
请参阅关于Multiset的Guava用户指南文章。
代码示例来源:origin: google/guava
public void testCreateWithSize() {
Multiset<String> multiset = HashMultiset.create(50);
multiset.add("foo", 2);
multiset.add("bar");
assertEquals(3, multiset.size());
assertEquals(2, multiset.count("foo"));
}
代码示例来源:origin: google/guava
@CollectionSize.Require(absent = ZERO)
@CollectionFeature.Require(SUPPORTS_REMOVE)
public void testElementSetRemovePropagatesToMultiset() {
Set<E> elementSet = getMultiset().elementSet();
int size = getNumElements();
int expectedSize = size - getMultiset().count(e0());
assertTrue(elementSet.remove(e0()));
assertFalse(getMultiset().contains(e0()));
assertEquals(expectedSize, getMultiset().size());
}
代码示例来源:origin: google/guava
@VisibleForTesting
ImmutableMultiset<E> buildJdkBacked() {
if (contents.isEmpty()) {
return of();
}
return JdkBackedImmutableMultiset.create(contents.entrySet());
}
}
代码示例来源:origin: google/guava
/** An implementation of {@link Multiset#setCount(Object, int)}. */
static <E> int setCountImpl(Multiset<E> self, E element, int count) {
checkNonnegative(count, "count");
int oldCount = self.count(element);
int delta = count - oldCount;
if (delta > 0) {
self.add(element, delta);
} else if (delta < 0) {
self.remove(element, -delta);
}
return oldCount;
}
代码示例来源:origin: google/guava
@CollectionSize.Require(absent = ZERO)
public void testEquals_differentElements() {
Multiset<E> other = HashMultiset.create(getSampleElements());
other.remove(e0());
other.add(e3());
assertFalse("multiset equals a multiset with different elements", getMultiset().equals(other));
}
代码示例来源:origin: SonarSource/sonarqube
@Nullable
@Override
public Integer apply(@Nonnull String language) {
return multiset.count(language);
}
}
代码示例来源:origin: caskdata/coopr
@Test
public void testSimpleIterator() {
NodeLayout masterNodeLayout = new NodeLayout("large", "centos6", ImmutableSet.of("master1"));
NodeLayout slaveLayout = new NodeLayout("medium", "centos6", ImmutableSet.of("slave1"));
Multiset<NodeLayout> counts = HashMultiset.create();
counts.add(masterNodeLayout);
counts.add(slaveLayout);
ClusterLayout layout = new ClusterLayout(constraints, counts);
Iterator<ClusterLayoutChange> iter = new AddServiceChangeIterator(layout, "slave2");
// only possible change is to add slave2 to the slave node
List<ClusterLayoutChange> expected = Lists.newArrayList();
Multiset<NodeLayout> expectedCounts = HashMultiset.create();
expectedCounts.add(slaveLayout);
expected.add(new AddServicesChange(expectedCounts, "slave2"));
assertIterator(expected, iter);
}
代码示例来源:origin: apache/mahout
public void testHashFloat() {
Multiset<Integer> violations = HashMultiset.create();
for (int k = 0; k < 1000; k++) {
List<Float> original = Lists.newArrayList();
Random gen = RandomUtils.getRandom();
for (int i = 0; i < 10000; i++) {
float x = (float) gen.nextDouble();
original.add(x);
}
violations.add(checkCounts(original) <= 12 ? 0 : 1);
}
// the hashes for floats don't really have 32 bits of entropy so the test
// only succeeds at better than about 99% rate.
assertTrue(violations.count(0) >= 985);
}
代码示例来源:origin: com.google.collections/google-collections
@Override public boolean equals(@Nullable Object object) {
if (object instanceof Multiset) {
Multiset<?> that = (Multiset<?>) object;
return this.size() == that.size() && delegate.equals(that.elementSet());
}
return false;
}
代码示例来源:origin: immutables/immutables
private void checkAttributeNamesForDuplicates(ValueType type, Protoclass protoclass) {
if (!type.attributes.isEmpty()) {
Multiset<String> attributeNames = HashMultiset.create(type.attributes.size());
for (ValueAttribute attribute : type.attributes) {
if (attribute.isGenerateLazy) {
attributeNames.add(attribute.name() + "$lazy"); // making lazy compare in it's own scope
} else {
attributeNames.add(attribute.name());
}
}
List<String> duplicates = Lists.newArrayList();
for (Multiset.Entry<String> entry : attributeNames.entrySet()) {
if (entry.getCount() > 1) {
duplicates.add(entry.getElement().replace("$lazy", ""));
}
}
if (!duplicates.isEmpty()) {
protoclass.report()
.error("Duplicate attribute names %s. You should check if correct @Value.Style applied",
duplicates);
}
}
}
代码示例来源:origin: caskdata/coopr
@Test
public void testValidLayout() {
NodeLayout masterNodeLayout = new NodeLayout("large-mem", "centos6", ImmutableSet.of("namenode"));
NodeLayout slaveLayout = new NodeLayout("medium", "centos6", ImmutableSet.of("datanode"));
NodeLayout reactorLayout = new NodeLayout("medium", "centos6", ImmutableSet.of("reactor", "zookeeper"));
Multiset<NodeLayout> counts = HashMultiset.create();
counts.add(masterNodeLayout);
counts.add(reactorLayout);
counts.add(slaveLayout, 50);
ClusterLayout layout = new ClusterLayout(constraints, counts);
Assert.assertTrue(layout.isValid());
}
代码示例来源:origin: education-service/speech-mfcc
/**
* A method to split a dataset into two datasets by a specified percentage. This method is class-aware.
* It will ensure that "percentage" of the observations for each class make it into the training data set.
* The remaining observations will be put into the testing data set.
*
* @param percentage
* @return Dataset[]
*/
public Dataset[] split(int percentage) {
generateClassCountsIfAbsent();
Multiset<String> splitCounts = HashMultiset.create();
List<Observation> trainingObservations = Lists.newArrayList();
List<Observation> testingObservations = Lists.newArrayList();
for (Observation observation : observations) {
if (getCountServedToTraining(splitCounts, observation) <= (percentage / 100D)) {
trainingObservations.add(observation);
} else {
testingObservations.add(observation);
}
splitCounts.add(observation.getClazz());
}
return new Dataset[] { new Dataset(trainingObservations, classMetadata),
new Dataset(testingObservations, classMetadata) };
}
代码示例来源:origin: edu.cmu.ml.rtw/matt-util
/**
* Assert that each of the lines passed in has been written, but don't care about the order.
*/
public void expectWritten(Collection<String> lines) {
TestCase.assertEquals("File: " + filename, lines.size(), written.size());
Multiset<String> counts = HashMultiset.create(lines);
for (Multiset.Entry<String> entry : counts.entrySet()) {
TestUtil.assertCount(written, entry.getElement(), entry.getCount());
}
written = Lists.newArrayList();
}
代码示例来源:origin: com.google.guava/guava-jdk5
@Override
public int add(@Nullable E element, int occurrences) {
checkArgument(predicate.apply(element),
"Element %s does not match predicate %s", element, predicate);
return unfiltered.add(element, occurrences);
}
代码示例来源:origin: com.google.guava/guava-jdk5
@Override
public boolean equals(@Nullable Object object) {
if (object instanceof Multiset) {
Multiset<?> other = (Multiset<?>) object;
return other.isEmpty();
}
return false;
}
代码示例来源:origin: thinkaurelius/titan
final Set<String> names = ImmutableSet.of("Marko", "Dan", "Stephen", "Daniel", "Josh", "Thad", "Pavel", "Matthias");
final int numG = 10;
final long[] gids = new long[numG];
Multiset<Integer> partitions = HashMultiset.create();
partitions.add(partition);
txx.commit();
assertTrue(partitions.elementSet().size() >= 3); //
int numV = 0;
while (parts.size() < numP) {
int part = Iterables.get(partitions.elementSet(), random.nextInt(partitions.elementSet().size()));
if (parts.add(part)) numV += partitions.count(part);
代码示例来源:origin: com.github.tomakehurst/wiremock-jre8
public List<StubMapping> process(Iterable<StubMapping> stubMappings) {
final Multiset<RequestPattern> requestCounts = HashMultiset.create();
final List<StubMapping> processedStubMappings = new ArrayList<>();
for (StubMapping stubMapping: stubMappings) {
requestCounts.add(stubMapping.getRequest());
// Skip duplicate requests if shouldRecordRepeatsAsScenarios is not enabled
if (
requestCounts.count(stubMapping.getRequest()) > 1
&& !shouldRecordRepeatsAsScenarios
) {
continue;
}
if (bodyExtractMatcher != null && bodyExtractMatcher.match(stubMapping.getResponse()).isExactMatch()) {
bodyExtractor.extractInPlace(stubMapping);
}
processedStubMappings.add(stubMapping);
}
if (shouldRecordRepeatsAsScenarios) {
new ScenarioProcessor().putRepeatedRequestsInScenarios(processedStubMappings);
}
// Run any stub mapping transformer extensions
return Lists.transform(processedStubMappings, transformerRunner);
}
}
代码示例来源:origin: google/guava
public void testCreateWithSize() {
Multiset<String> multiset = LinkedHashMultiset.create(50);
multiset.add("foo", 2);
multiset.add("bar");
assertEquals(3, multiset.size());
assertEquals(2, multiset.count("foo"));
assertEquals("[foo x 2, bar]", multiset.toString());
}
代码示例来源:origin: google/guava
@GwtIncompatible // SerializableTester
public void testSerializationContainingSelf() {
Multiset<Multiset<?>> multiset = HashMultiset.create();
multiset.add(multiset, 2);
Multiset<Multiset<?>> copy = SerializableTester.reserialize(multiset);
assertEquals(2, copy.size());
assertSame(copy, copy.iterator().next());
}
代码示例来源:origin: google/guava
public void testCopyOf_multiset_empty() {
Multiset<String> c = HashMultiset.create();
Multiset<String> multiset = ImmutableSortedMultiset.copyOf(c);
assertTrue(multiset.isEmpty());
}
内容来源于网络,如有侵权,请联系作者删除!