下面列出了怎么用com.google.common.collect.HashMultiset的API类实例代码及写法,或者点击链接到github查看源代码。
private Multiset<Integer> getBankItemSet()
{
ItemContainer itemContainer = client.getItemContainer(InventoryID.BANK);
if (itemContainer == null)
{
return HashMultiset.create();
}
Multiset<Integer> set = HashMultiset.create();
for (Item item : itemContainer.getItems())
{
if (item.getId() != ItemID.BANK_FILLER)
{
set.add(item.getId(), item.getQuantity());
}
}
return set;
}
public static void main(String[] args) {
// Parse text to separate words
String INPUT_TEXT = "Hello World! Hello All! Hi World!";
// Create Multiset
Multiset<String> multiset = HashMultiset.create(Arrays.asList(INPUT_TEXT.split(" ")));
// Print count words
System.out.println(multiset); // print [Hi, Hello x 2, World! x 2, All!] - in random orders
// Print all unique words
System.out.println(multiset.elementSet()); // print [Hi, Hello, World!, All!] - in random orders
// Print count occurrences of words
System.out.println("Hello = " + multiset.count("Hello")); // print 2
System.out.println("World = " + multiset.count("World!")); // print 2
System.out.println("All = " + multiset.count("All!")); // print 1
System.out.println("Hi = " + multiset.count("Hi")); // print 1
System.out.println("Empty = " + multiset.count("Empty")); // print 0
// Print count all words
System.out.println(multiset.size()); //print 6
// Print count unique words
System.out.println(multiset.elementSet().size()); //print 4
}
@Test
public void testSingleStatementPattern() throws Exception {
// Insert data
insert(OWL.THING, RDF.TYPE, OWL.CLASS);
insert(FOAF.PERSON, RDF.TYPE, OWL.CLASS, 1);
insert(FOAF.PERSON, RDFS.SUBCLASSOF, OWL.THING);
insert(VF.createIRI("urn:Alice"), RDF.TYPE, FOAF.PERSON);
dao.flush();
// Define query and expected results
final String query = "SELECT * WHERE {\n"
+ " ?individual a ?type .\n"
+ "}";
final List<String> varNames = Arrays.asList("individual", "type");
final Multiset<BindingSet> expectedSolutions = HashMultiset.create();
expectedSolutions.add(new ListBindingSet(varNames, OWL.THING, OWL.CLASS));
expectedSolutions.add(new ListBindingSet(varNames, FOAF.PERSON, OWL.CLASS));
expectedSolutions.add(new ListBindingSet(varNames, VF.createIRI("urn:Alice"), FOAF.PERSON));
// Execute pipeline and verify results
testPipelineQuery(query, expectedSolutions);
}
private static void assertBalancing(BucketBalancer balancer, int expectedMoves)
{
int actualMoves = balancer.balance();
assertEquals(actualMoves, expectedMoves);
// check that number of buckets per node is within bounds
ClusterState clusterState = balancer.fetchClusterState();
for (Distribution distribution : clusterState.getDistributionAssignments().keySet()) {
Multiset<String> allocationCounts = HashMultiset.create();
clusterState.getDistributionAssignments().get(distribution).stream()
.map(BucketAssignment::getNodeIdentifier)
.forEach(allocationCounts::add);
double bucketsPerNode = (1.0 * allocationCounts.size()) / clusterState.getActiveNodes().size();
for (String node : allocationCounts) {
assertGreaterThanOrEqual(allocationCounts.count(node), (int) Math.floor(bucketsPerNode), node + " has fewer buckets than expected");
assertLessThanOrEqual(allocationCounts.count(node), (int) Math.ceil(bucketsPerNode), node + " has more buckets than expected");
}
}
// check stability
assertEquals(balancer.balance(), 0);
}
@Test
public void emptyMultimapReads() {
Multimap<String, Integer> multimap = ImmutableSortedKeyListMultimap.of();
assertThat(multimap).doesNotContainKey("foo");
assertThat(multimap.containsValue(1)).isFalse();
assertThat(multimap).doesNotContainEntry("foo", 1);
assertThat(multimap.entries()).isEmpty();
assertThat(multimap.equals(ArrayListMultimap.create())).isTrue();
assertThat(multimap).valuesForKey("foo").isEqualTo(Collections.emptyList());
assertThat(multimap.hashCode()).isEqualTo(0);
assertThat(multimap).isEmpty();
assertThat(multimap.keys()).isEqualTo(HashMultiset.create());
assertThat(multimap).isEmpty();
assertThat(multimap).isEmpty();
assertThat(multimap).isEmpty();
assertThat(multimap.toString()).isEqualTo("{}");
}
/**
* Returns true if {@code atLeastM} of the expressions in the given column are the same kind.
*/
private static boolean expressionsAreParallel(
List<List<ExpressionTree>> rows, int column, int atLeastM) {
Multiset<Tree.Kind> nodeTypes = HashMultiset.create();
for (List<? extends ExpressionTree> row : rows) {
if (column >= row.size()) {
continue;
}
nodeTypes.add(row.get(column).getKind());
}
for (Multiset.Entry<Tree.Kind> nodeType : nodeTypes.entrySet()) {
if (nodeType.getCount() >= atLeastM) {
return true;
}
}
return false;
}
/**
* Gets properties of switched vlans.
*
* @param ctxt context in which to apply {@code interfacesSpecifier}
* @param configurations configuration to use in extractions
* @param nodes the set of nodes to consider
* @param interfaceSpecifier Specifies which interfaces to consider
* @param columns a map from column name to {@link ColumnMetadata}
* @return A multiset of {@link Row}s where each row corresponds to a node/vlan pair and columns
* correspond to property values.
*/
public static Multiset<Row> getProperties(
SpecifierContext ctxt,
Map<String, Configuration> configurations,
Set<String> nodes,
InterfaceSpecifier interfaceSpecifier,
boolean excludeShutInterfaces,
IntegerSpace vlans,
Map<String, ColumnMetadata> columns) {
Multiset<Row> rows = HashMultiset.create();
for (String node : nodes) {
Map<Integer, ImmutableSet.Builder<NodeInterfacePair>> switchedVlanInterfaces =
new HashMap<>();
ImmutableMap.Builder<Integer, Integer> vlanVnisBuilder = ImmutableMap.builder();
computeNodeVlanProperties(
ctxt,
configurations.get(node),
interfaceSpecifier,
excludeShutInterfaces,
vlans,
switchedVlanInterfaces,
vlanVnisBuilder);
populateNodeRows(node, switchedVlanInterfaces, vlanVnisBuilder, columns, rows);
}
return rows;
}
/**
* Make an abbreviated list of trains, like "2(6) 3(5)" etc, to show in the
* IPO.
*/
public String makeListOfTrainCards() {
if (trainCards.isEmpty()) return "";
// create a bag with train types
Multiset<TrainCardType> trainCardTypes = HashMultiset.create();
for (TrainCard card:trainCards) {
trainCardTypes.add(card.getType());
}
StringBuilder b = new StringBuilder();
for (TrainCardType cardType:ImmutableSortedSet.copyOf(trainCardTypes.elementSet())) {
if (b.length() > 0) b.append(" ");
b.append(cardType.toText()).append("(");
if (cardType.hasInfiniteQuantity()) {
b.append("+");
} else {
b.append(trainCardTypes.count(cardType));
}
b.append(")");
}
return b.toString();
}
@Test
public void testSimpleITE() {
Multiset<Node> components = HashMultiset.create();
components.add(BoolConst.TRUE);
components.add(IntConst.of(0));
components.add(IntConst.of(1));
components.add(Library.ITE);
ArrayList<TestCase> testSuite = new ArrayList<>();
Map<ProgramVariable, Node> assignment1 = new HashMap<>();
TestCase testCase1 = TestCase.ofAssignment(assignment1, IntConst.of(0));
testCase1.setId("t1");
testSuite.add(testCase1);
Synthesis synthesizerWithForbidden = new Synthesis(new BoundedShape(3, IntType.TYPE), new TreeBoundedEncoder());
Optional<Pair<Expression, Map<Parameter, Constant>>> result = synthesizerWithForbidden.synthesize(testSuite, components);
assertTrue(result.isPresent());
}
@Override
public void onTraversalStart() {
validateArguments();
metadata = MetadataUtils.fromHeader(getHeaderForReads(), Metadata.Type.SAMPLE_LOCATABLE);
final SAMSequenceDictionary sequenceDictionary = getBestAvailableSequenceDictionary();
//this check is currently redundant, since the master dictionary is taken from the reads;
//however, if any other dictionary is added in the future, such a check should be performed
if (!CopyNumberArgumentValidationUtils.isSameDictionary(metadata.getSequenceDictionary(), sequenceDictionary)) {
logger.warn("Sequence dictionary in BAM does not match the master sequence dictionary.");
}
intervals = intervalArgumentCollection.getIntervals(sequenceDictionary);
intervalMultiset = HashMultiset.create(intervals.size());
logger.info("Collecting read counts...");
}
private void writeCatList(Multiset<Category> cats, File outputFile) throws IOException {
Multiset<Category> catsNoPPorPRfeatures = HashMultiset.create();
for (Category cat : cats) {
catsNoPPorPRfeatures.add(cat.dropPPandPRfeatures());
}
FileWriter fw = new FileWriter(outputFile.getAbsoluteFile());
BufferedWriter bw = new BufferedWriter(fw);
int categories = 0;
for (Category type : Multisets.copyHighestCountFirst(cats).elementSet()) {
if (catsNoPPorPRfeatures.count(type.dropPPandPRfeatures()) >= 10) {
bw.write(type.toString());
bw.newLine();
categories++;
}
}
System.out.println("Number of cats occurring 10 times: " + categories);
bw.flush();
bw.close();
}
/**
* Handling containers that are completed.
*/
private void handleCompleted(List<YarnContainerStatus> completedContainersStatuses) {
Multiset<String> restartRunnables = HashMultiset.create();
for (YarnContainerStatus status : completedContainersStatuses) {
LOG.info("Container {} completed with {}:{}.",
status.getContainerId(), status.getState(), status.getDiagnostics());
runningContainers.handleCompleted(status, restartRunnables);
}
for (Multiset.Entry<String> entry : restartRunnables.entrySet()) {
LOG.info("Re-request container for {} with {} instances.", entry.getElement(), entry.getCount());
runnableContainerRequests.add(createRunnableContainerRequest(entry.getElement(), entry.getCount()));
}
// For all runnables that needs to re-request for containers, update the expected count timestamp
// so that the EventHandler would triggered with the right expiration timestamp.
expectedContainers.updateRequestTime(restartRunnables.elementSet());
}
@VisibleForTesting
static Multiset<Row> getLayer1Edges(
Set<String> includeNodes,
Set<String> includeRemoteNodes,
@Nullable Layer1Topology layer1Topology) {
if (layer1Topology == null) {
return HashMultiset.create();
}
return layer1Topology.getGraph().edges().stream()
.filter(
layer1Edge ->
includeNodes.contains(layer1Edge.getNode1().getHostname())
&& includeRemoteNodes.contains(layer1Edge.getNode2().getHostname()))
.map(EdgesAnswerer::layer1EdgeToRow)
.collect(Collectors.toCollection(HashMultiset::create));
}
private void processInventoryLoot(String event, LootRecordType lootRecordType, ItemContainer inventoryContainer, Collection<ItemStack> groundItems)
{
if (inventorySnapshot != null)
{
Multiset<Integer> currentInventory = HashMultiset.create();
Arrays.stream(inventoryContainer.getItems())
.forEach(item -> currentInventory.add(item.getId(), item.getQuantity()));
groundItems.stream()
.forEach(item -> currentInventory.add(item.getId(), item.getQuantity()));
final Multiset<Integer> diff = Multisets.difference(currentInventory, inventorySnapshot);
List<ItemStack> items = diff.entrySet().stream()
.map(e -> new ItemStack(e.getElement(), e.getCount(), client.getLocalPlayer().getLocalLocation()))
.collect(Collectors.toList());
addLoot(event, -1, lootRecordType, items);
inventorySnapshot = null;
}
}
/**
* Method should return the number of times an occurrence of a reel
*
* @param reels
* @return
*/
static int determinePayOutPercentage(List<String> reels) {
Multiset<String> reelCount = HashMultiset.create();
reelCount.addAll(reels);
// order the number of elements by the higest
ImmutableMultiset<String> highestCountFirst = Multisets.copyHighestCountFirst(reelCount);
int count = 0;
for (Entry<String> entry : highestCountFirst.entrySet()) {
count = entry.getCount();
break;
}
return count;
}
@Override
public void attachAnchored(IVisualPart<? extends Node> anchored) {
// determine the viewer before adding the anchored
IViewer oldViewer = getViewer();
// register if we obtain a link to the viewer
HashMultiset<IVisualPart<? extends Node>> newAnchoreds = HashMultiset
.create(anchoreds);
newAnchoreds.add(anchored);
IViewer newViewer = determineViewer(getParent(), newAnchoreds);
// unregister from old viewer in case we were registered (oldViewer !=
// null) and the viewer changes (newViewer != oldViewer)
if (oldViewer != null && newViewer != oldViewer) {
oldViewer.unsetAdapter(this);
}
// detach anchoreds (and fire change notifications)
anchoreds.add(anchored);
// if we obtain a link to the viewer then register at new viewer
if (newViewer != null && newViewer != oldViewer) {
newViewer.setAdapter(this,
String.valueOf(System.identityHashCode(this)));
}
}
/**
* Sorts the list of triplesMapBuilders
* Taken from https://en.wikipedia.org/wiki/Topological_sorting#Depth-first_search
*
* <p>
* L ← Empty list that will contain the sorted nodes
* while there are unvisited nodes do
* select an unvisited node current
* visit(current, L)
* </p>
*
* @param input the original list of triplesMapBuilders
* @param lookup a lookup table to link URI's to their tripleMap objects
* @param onCycle code to handle a cycle if it occurs
* @param errorConsumer code to handle errors reported by this method (i.e. log it, throw it, do what you want)
* @return the sorted list of builders
*/
public static LinkedList<TriplesMapBuilder> topologicalSort(List<TriplesMapBuilder> input,
Map<String, TriplesMapBuilder> lookup,
TopologicalSorter.CycleConsumer onCycle,
Consumer<String> errorConsumer) {
Set<TriplesMapBuilder> unvisited = input.stream().collect(Collectors.toSet()); //copy so we don't modify the input
// L ← Empty list that will contain the sorted nodes
LinkedList<TriplesMapBuilder> result = Lists.newLinkedList();
// while there are unvisited nodes do
while (!unvisited.isEmpty()) {
// select an unvisited node n
TriplesMapBuilder current = unvisited.iterator().next();
// visit(n)
sortStep(current, result, HashMultiset.create(), lookup, unvisited, onCycle, errorConsumer);
}
return result;
}
/** Returns true if {@code atLeastM} of the expressions in the given column are the same kind. */
private static boolean expressionsAreParallel(
List<List<ExpressionTree>> rows, int column, int atLeastM) {
Multiset<Tree.Kind> nodeTypes = HashMultiset.create();
for (List<? extends ExpressionTree> row : rows) {
if (column >= row.size()) {
continue;
}
// Treat UnaryTree expressions as their underlying type for the comparison (so, for example
// -ve and +ve numeric literals are considered the same).
if (row.get(column) instanceof UnaryTree) {
nodeTypes.add(((UnaryTree) row.get(column)).getExpression().getKind());
} else {
nodeTypes.add(row.get(column).getKind());
}
}
for (Multiset.Entry<Tree.Kind> nodeType : nodeTypes.entrySet()) {
if (nodeType.getCount() >= atLeastM) {
return true;
}
}
return false;
}
/**
* Produces the set difference of two sequences by
* using the specified {@code EqualityComparer<TSource>} to compare
* values, using {@code all} to indicate whether to eliminate duplicates.
*/
public static <TSource> Enumerable<TSource> except(
Enumerable<TSource> source0, Enumerable<TSource> source1,
EqualityComparer<TSource> comparer, boolean all) {
if (comparer == Functions.identityComparer()) {
return except(source0, source1, all);
}
Collection<Wrapped<TSource>> collection = all ? HashMultiset.create() : new HashSet<>();
Function1<TSource, Wrapped<TSource>> wrapper = wrapperFor(comparer);
source0.select(wrapper).into(collection);
try (Enumerator<Wrapped<TSource>> os =
source1.select(wrapper).enumerator()) {
while (os.moveNext()) {
Wrapped<TSource> o = os.current();
collection.remove(o);
}
}
Function1<Wrapped<TSource>, TSource> unwrapper = unwrapper();
return Linq4j.asEnumerable(collection).select(unwrapper);
}
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);
}
}
}
@Override
protected boolean classify(Device device) {
if (!super.classify(device)) {
String role;
// Does the device have any hosts attached? If not, it's a spine
if (hostService.getConnectedHosts(device.id()).isEmpty()) {
// Does the device have any aggregate links to other devices?
Multiset<DeviceId> destinations = HashMultiset.create();
linkService.getDeviceEgressLinks(device.id()).stream()
.map(l -> l.dst().deviceId()).forEach(destinations::add);
// If yes, it's the main spine; otherwise it's an aggregate spine
role = destinations.entrySet().stream().anyMatch(e -> e.getCount() > 1) ?
SPINE : AGGREGATION;
} else {
// Does the device have any multi-home hosts attached?
// If yes, it's a service leaf; otherwise it's an access leaf
role = hostService.getConnectedHosts(device.id()).stream()
.map(Host::locations).anyMatch(s -> s.size() > 1) ?
LEAF : ACCESS;
}
deviceCategories.put(role, device.id());
}
return true;
}
/**
* Example was modified from the guava site to remove
* periods
*
* @throws IOException
*/
@Test
public void count_distinct_words_in_file_guava () throws IOException {
File file = new File(sourceFileURI);
Multiset<String> wordOccurrences = HashMultiset.create(
Splitter.on(CharMatcher.WHITESPACE)
.trimResults(CharMatcher.is('.'))
.omitEmptyStrings()
.split(Files.asCharSource(file, Charsets.UTF_8).read()));
logger.info(wordOccurrences);
assertEquals(80, wordOccurrences.elementSet().size());
}
public void testSerialization() {
BeanWithMultisetTypes bean = new BeanWithMultisetTypes();
List<String> list = Arrays.asList( "foo", "abc", null, "abc" );
List<String> listWithNonNull = Arrays.asList( "foo", "abc", "bar", "abc" );
bean.multiset = LinkedHashMultiset.create( list );
bean.hashMultiset = HashMultiset.create( Arrays.asList( "abc", "abc" ) );
bean.linkedHashMultiset = LinkedHashMultiset.create( list );
bean.sortedMultiset = TreeMultiset.create( listWithNonNull );
bean.treeMultiset = TreeMultiset.create( listWithNonNull );
bean.immutableMultiset = ImmutableMultiset.copyOf( listWithNonNull );
bean.enumMultiset = EnumMultiset.create( Arrays.asList( AlphaEnum.B, AlphaEnum.A, AlphaEnum.D, AlphaEnum.A ) );
String expected = "{" +
"\"multiset\":[\"foo\",\"abc\",\"abc\",null]," +
"\"hashMultiset\":[\"abc\",\"abc\"]," +
"\"linkedHashMultiset\":[\"foo\",\"abc\",\"abc\",null]," +
"\"sortedMultiset\":[\"abc\",\"abc\",\"bar\",\"foo\"]," +
"\"treeMultiset\":[\"abc\",\"abc\",\"bar\",\"foo\"]," +
"\"immutableMultiset\":[\"foo\",\"abc\",\"abc\",\"bar\"]," +
"\"enumMultiset\":[\"A\",\"A\",\"B\",\"D\"]" +
"}";
assertEquals( expected, BeanWithMultisetTypesMapper.INSTANCE.write( bean ) );
}
/**
* Get the lowest utilized data storage location
* @return
*/
public String getLocationLowestUtilizedDataLocation() {
final Multiset<String> usage = HashMultiset.create();
// Put every location into the table (even unused ones)
storages.keySet().forEach(s -> usage.add(s));
// Add SSTables per storage usage
tupleStoreLocations.values().forEach(v -> usage.add(v));
// Return the lowest usage
return usage.entrySet().stream()
.reduce((a,b) -> a.getCount() < b.getCount() ? a : b)
.get()
.getElement();
}
static boolean unorderedEquals(List<FlamdexDocument> l1, List<FlamdexDocument> l2) {
if (l1.size() != l2.size()) return false;
Multiset<FlamdexDocumentWrapper> s1 = HashMultiset.create(Lists.transform(l1, new Function<FlamdexDocument, FlamdexDocumentWrapper>() {
@Override
public FlamdexDocumentWrapper apply(FlamdexDocument input) {
return new FlamdexDocumentWrapper(input);
}
}));
for (final FlamdexDocument doc : l2) {
final FlamdexDocumentWrapper w = new FlamdexDocumentWrapper(doc);
if (!s1.remove(w)) return false;
}
return s1.isEmpty();
}
@Test
public void testNoVariableSP() throws Exception {
// Insert data
insert(OWL.THING, RDF.TYPE, OWL.CLASS);
insert(FOAF.PERSON, RDF.TYPE, OWL.CLASS, 1);
insert(FOAF.PERSON, RDFS.SUBCLASSOF, OWL.THING);
insert(VF.createIRI("urn:Alice"), RDF.TYPE, FOAF.PERSON);
dao.flush();
// Define query and expected results
final String query = "SELECT * WHERE {\n"
+ " owl:Thing a owl:Class .\n"
+ "}";
final Multiset<BindingSet> expectedSolutions = HashMultiset.create();
expectedSolutions.add(new EmptyBindingSet());
// Execute pipeline and verify results
final QueryRoot queryTree = new QueryRoot(PARSER.parseQuery(query, null).getTupleExpr());
final SparqlToPipelineTransformVisitor visitor = new SparqlToPipelineTransformVisitor(getRyaCollection());
queryTree.visit(visitor);
Assert.assertTrue(queryTree.getArg() instanceof Projection);
final Projection projection = (Projection) queryTree.getArg();
Assert.assertTrue(projection.getArg() instanceof AggregationPipelineQueryNode);
final AggregationPipelineQueryNode pipelineNode = (AggregationPipelineQueryNode) projection.getArg();
final Multiset<BindingSet> solutions = HashMultiset.create();
final CloseableIteration<BindingSet, QueryEvaluationException> iter = pipelineNode.evaluate(new QueryBindingSet());
while (iter.hasNext()) {
solutions.add(iter.next());
}
Assert.assertEquals(expectedSolutions, solutions);
}
public FoldableNode(final ASTNode n) {
termFreqs = HashMultiset.create();
children = Lists.newArrayList();
node = n;
nodeID = nodeCount;
nodeCount++;
}
public void testStrategyProportional() throws Exception {
HttpPostGet http = new HttpPostGet();
String bid = Charset.defaultCharset()
.decode(ByteBuffer.wrap(Files.readAllBytes(Paths.get("./SampleBids/rotating.txt")))).toString();
Multiset<String> mm = HashMultiset.create();
ProportionalRandomCollection pr = new ProportionalRandomCollection("apples");
pr.addEntry("ASFFJKL","c3",10000);
pr.addEntry("c2",500);
pr.addEntry("c1",100);
pr.commit();
try {
String s = null;
for (int i=0;i<100;i++) {
try {
s = http.sendPost("http://" + Config.testHost + "/rtb/bids/c1x", bid, 100000, 100000);
} catch (Exception error) {
fail("Can't connect to test host: " + Config.testHost);
}
assertNotNull(s);
String crid = extractCrid(s);
mm.add(crid);
}
//int count = mm.count("c1");
//assertNotEquals(count,10);
System.out.println("-------------->"+mm);
} catch (Exception e) {
e.printStackTrace();
fail(e.toString());
}
}
private static void addNerTypeLabel(String token, BmeowTypePair pair) {
Multiset<BmeowTypePair> labelCount = classTypeCounts.get(token);
if(labelCount == null){
labelCount = HashMultiset.create();
}
labelCount.add(pair);
classTypeCounts.put(token, labelCount);
}
private static void addNerTypeLabel(String token, Label label) {
Multiset<Label> labelCount = classTypeCounts.get(token);
if(labelCount == null){
labelCount = HashMultiset.create();
}
labelCount.add(label);
classTypeCounts.put(token, labelCount);
}