Example usage for com.google.common.collect Multiset add

List of usage examples for com.google.common.collect Multiset add

Introduction

In this page you can find the example usage for com.google.common.collect Multiset add.

Prototype

@Override
boolean add(E element);

Source Link

Document

Adds a single occurrence of the specified element to this multiset.

Usage

From source file:com.opengamma.strata.report.framework.expression.IterableTokenEvaluator.java

@Override
public Set<String> tokens(Iterable<?> iterable) {
    Multiset<String> tokens = HashMultiset.create();
    int index = 0;

    for (Object item : iterable) {
        tokens.add(String.valueOf(index++));
        tokens.addAll(fieldValues(item));
    }/* w  w w  .ja  v a 2s .co m*/
    return tokens.stream().filter(token -> tokens.count(token) == 1).collect(toImmutableSet());
}

From source file:org.sonar.plugins.core.sensors.ViolationsDecorator.java

private void computeViolationsPerRules(DecoratorContext context) {
    Map<RulePriority, Multiset<Rule>> rulesPerSeverity = Maps.newHashMap();
    for (Violation violation : context.getViolations()) {
        Multiset<Rule> rulesBag = initRules(rulesPerSeverity, violation.getSeverity());
        rulesBag.add(violation.getRule());
    }//from   w  w  w  .j a  v  a 2s .  co m

    for (RulePriority severity : RulePriority.values()) {
        Metric metric = SeverityUtils.severityToViolationMetric(severity);

        Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.rules(metric));
        for (Measure child : children) {
            RuleMeasure childRuleMeasure = (RuleMeasure) child;
            Rule rule = childRuleMeasure.getRule();
            if (rule != null && MeasureUtils.hasValue(childRuleMeasure)) {
                Multiset<Rule> rulesBag = initRules(rulesPerSeverity, severity);
                rulesBag.add(rule, childRuleMeasure.getIntValue());
            }
        }

        Multiset<Rule> rulesBag = rulesPerSeverity.get(severity);
        if (rulesBag != null) {
            for (Multiset.Entry<Rule> entry : rulesBag.entrySet()) {
                RuleMeasure measure = RuleMeasure.createForRule(metric, entry.getElement(),
                        (double) entry.getCount());
                measure.setSeverity(severity);
                context.saveMeasure(measure);
            }
        }
    }
}

From source file:com.sun.tools.hat.internal.server.FinalizerSummaryQuery.java

private void printFinalizerSummary(Collection<? extends JavaHeapObject> objs) {
    int count = 0;
    Multiset<JavaClass> bag = HashMultiset.create();

    for (JavaHeapObject obj : objs) {
        count++;/*from www. j a  va2  s.  co  m*/
        bag.add(obj.getClazz());
    }

    out.println("<p align='center'>");
    out.println("<b>");
    out.println("Total ");
    if (count != 0) {
        out.print("<a href='/finalizerObjects/'>instances</a>");
    } else {
        out.print("instances");
    }
    out.println(" pending finalization: ");
    out.print(count);
    out.println("</b></p><hr>");

    if (count == 0) {
        return;
    }

    // calculate and print histogram
    out.println("<table border=1 align=center>");
    out.println("<tr><th>Count</th><th>Class</th></tr>");
    bag.entrySet().stream().sorted(Ordering.natural().reverse().onResultOf(entry -> entry.getCount()))
            .forEach(entry -> {
                out.println("<tr><td>");
                out.println(entry.getCount());
                out.println("</td><td>");
                printClass(entry.getElement());
                out.println("</td><tr>");
            });
    out.println("</table>");
}

From source file:com.textocat.textokit.commons.wfstore.DefaultWordformStoreBuilder.java

@Override
public void increment(String wordString, TagType tag) {
    Multiset<TagType> tags = strKeyMap.get(wordString);
    if (tags == null) {
        tags = HashMultiset.create();//from w  ww  .  j a va  2  s.  c  o m
        strKeyMap.put(wordString, tags);
    }
    tags.add(tag);
}

From source file:org.sonar.plugins.core.sensors.ViolationsDecorator.java

private void computeViolationsPerSeverities(DecoratorContext context) {
    Multiset<RulePriority> severitiesBag = HashMultiset.create();
    for (Violation violation : context.getViolations()) {
        severitiesBag.add(violation.getSeverity());
    }/*from   w w  w  .  j  a  v  a  2s  .c  om*/

    for (RulePriority severity : RulePriority.values()) {
        Metric metric = SeverityUtils.severityToViolationMetric(severity);
        if (context.getMeasure(metric) == null) {
            Collection<Measure> children = context.getChildrenMeasures(MeasuresFilters.metric(metric));
            int sum = MeasureUtils.sum(true, children).intValue() + severitiesBag.count(severity);
            context.saveMeasure(metric, (double) sum);
        }
    }
}

From source file:master.conditions.LeafCountPostSimCondition.java

/**
 * Returns true iff the given inheritance trajectory
 * meet the post-simulation acceptance condition.
 * /*from w  ww. j av  a 2  s  .c o  m*/
 * @param itraj inheritance trajectory
 * @return true if the end condition is met.
 */
@Override
public boolean accept(InheritanceTrajectory itraj) {

    // Assemble leaf counts:
    Multiset<Population> leafCounts = HashMultiset.create();
    for (Node leaf : itraj.getEndNodes())
        leafCounts.add(leaf.getPopulation());

    // Check whether condition is met:
    int size;
    if (populationInput.get().isEmpty())
        size = leafCounts.size();
    else {
        size = 0;
        for (Population pop : populationInput.get())
            size += leafCounts.count(pop);
    }

    if (exact)
        return size == nTerminalNodes;

    if (exceed)
        return size >= nTerminalNodes;
    else
        return size <= nTerminalNodes;
}

From source file:org.softinica.maven.jmeter.report.analyser.ThroughputAnalyzer.java

@Override
protected JFreeChart createChart(PageDefinition definition, Input input) {
    Map<String, Multiset<Long>> allSeries = new HashMap<String, Multiset<Long>>();
    for (Sample sample : input.getSamples()) {
        Multiset<Long> rps = allSeries.get(sample.getLabel());
        if (rps == null) {
            rps = TreeMultiset.create();
            allSeries.put(sample.getLabel(), rps);
        }//from  w ww . j ava  2  s .c om
        rps.add(((sample.getTimestamp() + (long) sample.getValue()) / 1000) * 1000);
    }
    TimeSeriesCollection dataset = new TimeSeriesCollection();
    for (String label : allSeries.keySet()) {
        Multiset<Long> rps = allSeries.get(label);
        TimeSeries series = new TimeSeries(label);
        for (Long key : rps) {
            series.addOrUpdate(new Second(new Date(key)), rps.count(key));
        }
        dataset.addSeries(series);
    }

    return ChartFactory.createTimeSeriesChart(definition.getTitle(), "Time", "Requests/second", dataset);
}

From source file:org.mitre.openid.connect.service.impl.DefaultStatsService.java

private Map<Long, Integer> computeByClientId() {
    // get all approved sites
    Collection<ApprovedSite> allSites = approvedSiteService.getAll();

    Multiset<String> clientIds = HashMultiset.create();
    for (ApprovedSite approvedSite : allSites) {
        clientIds.add(approvedSite.getClientId());
    }//from  w  w  w . j  a  va2s.  c o m

    Map<Long, Integer> counts = getEmptyClientCountMap();
    for (String clientId : clientIds) {
        ClientDetailsEntity client = clientService.loadClientByClientId(clientId);
        counts.put(client.getId(), clientIds.count(clientId));
    }

    return counts;
}

From source file:com.b2international.snowowl.snomed.datastore.index.update.ReferenceSetMembershipUpdater.java

private void processReferencingRefSetIds(final Multiset<String> memberOf,
        final Multiset<String> activeMemberOf) {
    memberChanges.stream().filter(c -> c.getChangeKind() == MemberChangeKind.ADDED).forEach(change -> {
        if (change.isActive()) {
            activeMemberOf.add(change.getRefSetId());
        }//w ww.  ja  v a  2s .  c  o m
        memberOf.add(change.getRefSetId());
    });

    memberChanges.stream().filter(c -> c.getChangeKind() == MemberChangeKind.CHANGED).forEach(change -> {
        // if the new state is active, then add it to the activeMemberOf otherwise remove it from that
        // this state transition won't change the memberOf field were all referring refsets are tracked
        if (change.isActive()) {
            activeMemberOf.add(change.getRefSetId());
        } else {
            activeMemberOf.remove(change.getRefSetId());
        }
    });

    memberChanges.stream().filter(c -> c.getChangeKind() == MemberChangeKind.REMOVED).forEach(change -> {
        if (change.isActive()) {
            activeMemberOf.remove(change.getRefSetId());
        }
        memberOf.remove(change.getRefSetId());
    });
}

From source file:com.mapr.storm.CounterBolt.java

/**
 * Records and then clears all pending counts if we have crossed a window boundary
 * or have a bunch of data accumulated or if forced.
 * @param force  If true, then windows and such are ignored and the data is pushed out regardless
 *//*from  w  w w  . ja  va 2 s  .c  o  m*/
private void recordCounts(boolean force) {
    long currentRecordWindowStart = (now() / reportingInterval) * reportingInterval;
    if (lastRecordOutput == 0) {
        lastRecordOutput = currentRecordWindowStart;
    }

    final int bufferedTuples = tupleLog.get().size();
    if (force || currentRecordWindowStart > lastRecordOutput || bufferedTuples > maxBufferedTuples) {
        if (force) {
            logger.info("Forced recording");
        } else if (bufferedTuples > maxBufferedTuples) {
            logger.info("Recording due to max tuples");
        } else {
            logger.info("Recording due to time");
        }

        // atomic get and set avoids the need to locks and still avoids races
        // grabbing the entire queue at once avoids contention as we count the queue elements
        Queue<Tuple> oldLog = tupleLog.getAndSet(new LinkedBlockingQueue<Tuple>());

        Multiset<String> counts = HashMultiset.create();
        for (Tuple tuple : oldLog) {
            counts.add(tuple.getString(0) + "\t" + tuple.getString(1));
        }

        // record all keys
        for (String keyValue : counts.elementSet()) {
            final int n = counts.count(keyValue);
            outputCollector.emit(oldLog, new Values(keyValue, n));
            count.addAndGet(n);
        }
        logger.info(String.format("Logged %d events", count.get()));

        for (Tuple tuple : oldLog) {
            outputCollector.ack(tuple);
        }
        lastRecordOutput = currentRecordWindowStart;
    }
}