Example usage for com.google.common.collect SetMultimap get

List of usage examples for com.google.common.collect SetMultimap get

Introduction

In this page you can find the example usage for com.google.common.collect SetMultimap get.

Prototype

@Override
Set<V> get(@Nullable K key);

Source Link

Document

Because a SetMultimap has unique values for a given key, this method returns a Set , instead of the java.util.Collection specified in the Multimap interface.

Usage

From source file:com.palantir.typescript.search.SearchResultTreeContentProvider.java

private void setSearchResult(SearchResult searchResult) {
    this.children.clear();

    for (Object element : searchResult.getElements()) {
        SetMultimap<Integer, FindReferenceMatch> matchesByLineNumber = TreeMultimap.create();

        // collect the matches for each line
        for (Match match : searchResult.getMatches(element)) {
            FindReferenceMatch findReferenceMatch = (FindReferenceMatch) match;
            int lineNumber = findReferenceMatch.getReference().getLineNumber();

            matchesByLineNumber.put(lineNumber, findReferenceMatch);
        }//from   ww  w. ja  v a2 s  . co m

        // add the lines
        for (Integer lineNumber : matchesByLineNumber.keySet()) {
            Set<FindReferenceMatch> lineMatches = matchesByLineNumber.get(lineNumber);
            LineResult lineResult = new LineResult(lineMatches);

            this.add(searchResult, lineResult);
        }
    }
}

From source file:org.terasology.module.ModuleEnvironment.java

private ImmutableSetMultimap<Name, Name> buildModuleDependencies() {
    SetMultimap<Name, Name> moduleDependenciesBuilder = HashMultimap.create();
    for (Module module : getModulesOrderedByDependencies()) {
        for (DependencyInfo dependency : module.getMetadata().getDependencies()) {
            moduleDependenciesBuilder.put(module.getId(), dependency.getId());
            moduleDependenciesBuilder.putAll(module.getId(), moduleDependenciesBuilder.get(dependency.getId()));
        }//from  w  w w  .jav a 2s.  c o  m
    }
    return ImmutableSetMultimap.copyOf(moduleDependenciesBuilder);
}

From source file:de.fau.osr.bl.Tracker.java

/**
 * This method returns all the requirements for the given File.
 *///ww w .  j a va2s  .com
@Deprecated
public Set<String> getRequirementIdsForFile(String filePath) throws IOException {
    String filename = filePath.replaceAll(Matcher.quoteReplacement("\\"), "/");
    Set<String> requirementList = new HashSet<>();

    Iterator<String> commitIdListIterator = vcsClient.getCommitListForFileodification(filename);
    SetMultimap<String, String> relations = getAllCommitReqRelations();

    while (commitIdListIterator.hasNext()) {
        requirementList.addAll(relations.get(commitIdListIterator.next()));
    }

    return requirementList;

}

From source file:com.puppycrawl.tools.checkstyle.checks.TranslationCheck.java

/**
 * Checks existence of translation files (arranged in a map)
 * for each resource bundle in project.//from   w  ww. ja v  a  2s.  co  m
 * @param translations the translation files bundles organized as Map.
 */
private void checkExistenceOfTranslations(SetMultimap<String, File> translations) {
    for (String fullyQualifiedBundleName : translations.keySet()) {
        final String bundleBaseName = extractName(fullyQualifiedBundleName);
        if (bundleBaseName.contains("messages")) {
            final Set<File> filesInBundle = translations.get(fullyQualifiedBundleName);
            checkExistenceOfDefaultTranslation(filesInBundle);
            checkExistenceOfRequiredTranslations(filesInBundle);
        }
    }
}

From source file:org.jetbrains.kotlin.resolve.calls.smartcasts.DelegatingDataFlowInfo.java

@NotNull
@Override/*  w w  w  . j  a  v a  2 s.  c om*/
public DataFlowInfo or(@NotNull DataFlowInfo otherInfo) {
    if (otherInfo == EMPTY)
        return EMPTY;
    if (this == EMPTY)
        return EMPTY;
    if (this == otherInfo)
        return this;

    assert otherInfo instanceof DelegatingDataFlowInfo : "Unknown DataFlowInfo type: " + otherInfo;
    DelegatingDataFlowInfo other = (DelegatingDataFlowInfo) otherInfo;

    Map<DataFlowValue, Nullability> nullabilityMapBuilder = Maps.newHashMap();
    for (Map.Entry<DataFlowValue, Nullability> entry : other.getCompleteNullabilityInfo().entrySet()) {
        DataFlowValue key = entry.getKey();
        Nullability otherFlags = entry.getValue();
        Nullability thisFlags = getNullability(key);
        nullabilityMapBuilder.put(key, thisFlags.or(otherFlags));
    }

    SetMultimap<DataFlowValue, KotlinType> myTypeInfo = getCompleteTypeInfo();
    SetMultimap<DataFlowValue, KotlinType> otherTypeInfo = other.getCompleteTypeInfo();
    SetMultimap<DataFlowValue, KotlinType> newTypeInfo = newTypeInfo();

    for (DataFlowValue key : Sets.intersection(myTypeInfo.keySet(), otherTypeInfo.keySet())) {
        Set<KotlinType> thisTypes = myTypeInfo.get(key);
        Set<KotlinType> otherTypes = otherTypeInfo.get(key);
        newTypeInfo.putAll(key, Sets.intersection(thisTypes, otherTypes));
    }

    if (nullabilityMapBuilder.isEmpty() && newTypeInfo.isEmpty()) {
        return EMPTY;
    }

    return new DelegatingDataFlowInfo(null, ImmutableMap.copyOf(nullabilityMapBuilder), newTypeInfo);
}

From source file:de.fau.osr.bl.Tracker.java

/**
 * creates/gets commit objects, by given ids.
 * @return set of commit objects/*from   w ww.ja va2  s .c o m*/
 * @throws IOException
 */
public Set<Commit> getCommitsByIds(Collection<String> commitIds) throws IOException {
    Set<Commit> commits = new HashSet<>();
    SetMultimap<String, String> relations = getAllCommitReqRelations();
    for (String id : commitIds) {
        commits.add(new Commit(id, vcsClient.getCommitMessage(id), relations.get(id),
                vcsClient.getCommitFiles(id)));
    }

    return commits;
}

From source file:org.sosy_lab.cpachecker.cpa.predicate.ImpactGlobalRefiner.java

/**
 * Recursively perform refinement on the subgraph of the ARG starting with a given state.
 * Each recursion step corresponds to one "block" of the ARG. As one block
 * may have several successors, this is recursion on a tree.
 * We proceed in a DFS order./*from w  w  w  .  j av a 2  s  . c  o m*/
 * Recursion stops as soon as the path has been determined to be infeasible
 * (so we do refinement as soon as possible) or a target state is reached
 * (then we found a feasible counterexample).
 * When an infeasible state was found, we call
 * {@link #performRefinementOnPath(List, ARGState, Map, ReachedSet)}
 * to do the actual refinement.
 *
 * Note that the successor and predecessor relation contains only states
 * that belong to paths to a target state, so we refine only such paths,
 * and not all paths in the ARG.
 *
 * @param current The ARG state that is the root of the to-be-refined ARG part.
 * @param itpStack The stack of interpolation groups added to the solver environment so far.
 * @param successors The successor relation between abstraction states.
 * @param predecessors The predecessor relation between abstraction states.
 * @param pReached The complete reached set.
 * @param targets The set of target states.
 * @return False if a feasible counterexample was found, True if refinement was successful.
 */
private <T> boolean step(ARGState current, List<T> itpStack, SetMultimap<ARGState, ARGState> successors,
        Map<ARGState, ARGState> predecessors, ReachedSet pReached, List<AbstractState> targets,
        InterpolatingProverEnvironment<T> itpProver) throws InterruptedException, CPAException {

    for (ARGState succ : successors.get(current)) {
        assert succ.getChildren().isEmpty() == targets.contains(succ);
        assert succ.mayCover();

        BooleanFormula blockFormula = getPredicateState(succ).getAbstractionFormula().getBlockFormula()
                .getFormula();
        itpStack.add(itpProver.push(blockFormula));
        try {
            satCheckTime.start();
            boolean isUnsat = itpProver.isUnsat();
            satCheckTime.stop();
            if (isUnsat) {
                logger.log(Level.FINE, "Found unreachable state", succ);
                performRefinementOnPath(unmodifiableList(itpStack), succ, predecessors, pReached, itpProver);

            } else if (targets.contains(succ)) {
                // We have found a reachable target state, immediately abort refinement.
                logger.log(Level.FINE, "Found reachable target state", succ);
                return false;

            } else {
                // Not yet infeasible, but path is longer,
                // so descend recursively.
                boolean successful = step(succ, itpStack, successors, predecessors, pReached, targets,
                        itpProver);

                if (!successful) {
                    return false;
                }
            }

            if (!current.mayCover()) {
                // The refinement along the current path made the current part of the ARG covered.
                // This may happens if some state up in the path was strengthened with
                // an interpolant and is now covered.
                // In this case, we do not need to do anything further in this part.
                break;
            }
        } finally {
            itpStack.remove(itpStack.size() - 1);
            itpProver.pop();
        }
    }
    return true;
}

From source file:com.facebook.buck.core.config.AbstractAliasConfig.java

/**
 * In a {@link BuckConfig}, an alias can either refer to a fully-qualified build target, or an
 * alias defined earlier in the {@code alias} section. The mapping produced by this method
 * reflects the result of resolving all aliases as values in the {@code alias} section.
 *//*  w  ww .  ja  va 2  s .c om*/
private ImmutableSetMultimap<String, BuildTarget> createAliasToBuildTargetMap(
        ImmutableMap<String, String> rawAliasMap) {
    // We use a LinkedHashMap rather than an ImmutableMap.Builder because we want both (1) order to
    // be preserved, and (2) the ability to inspect the Map while building it up.
    SetMultimap<String, BuildTarget> aliasToBuildTarget = LinkedHashMultimap.create();
    for (Map.Entry<String, String> aliasEntry : rawAliasMap.entrySet()) {
        String alias = aliasEntry.getKey();
        validateAliasName(alias);

        // Determine whether the mapping is to a build target or to an alias.
        List<String> values = Splitter.on(' ').splitToList(aliasEntry.getValue());
        for (String value : values) {
            Set<BuildTarget> buildTargets;
            if (isValidAliasName(value)) {
                buildTargets = aliasToBuildTarget.get(value);
                if (buildTargets.isEmpty()) {
                    throw new HumanReadableException("No alias for: %s.", value);
                }
            } else if (value.isEmpty()) {
                continue;
            } else {
                // Here we parse the alias values with a BuildTargetParser to be strict. We could be
                // looser and just grab everything between "//" and ":" and assume it's a valid base path.
                buildTargets = ImmutableSet.of(getDelegate().getBuildTargetForFullyQualifiedTarget(value,
                        EmptyTargetConfiguration.INSTANCE));
            }
            aliasToBuildTarget.putAll(alias, buildTargets);
        }
    }
    return ImmutableSetMultimap.copyOf(aliasToBuildTarget);
}

From source file:com.puppycrawl.tools.checkstyle.checks.TranslationCheck.java

/**
 * Compares the key sets of the given property files (arranged in a map)
 * with the specified key set. All missing keys are reported.
 * @param keys the set of keys to compare with
 * @param fileMap a Map from property files to their key sets
 *///from w  ww .  ja  va  2s. c  o m
private void compareKeySets(Set<Object> keys, SetMultimap<File, Object> fileMap) {

    for (File currentFile : fileMap.keySet()) {
        final MessageDispatcher dispatcher = getMessageDispatcher();
        final String path = currentFile.getPath();
        dispatcher.fireFileStarted(path);
        final Set<Object> currentKeys = fileMap.get(currentFile);

        // Clone the keys so that they are not lost
        final Set<Object> keysClone = Sets.newHashSet(keys);
        keysClone.removeAll(currentKeys);

        // Remaining elements in the key set are missing in the current file
        if (!keysClone.isEmpty()) {
            for (Object key : keysClone) {
                log(0, MSG_KEY, key);
            }
        }
        fireErrors(path);
        dispatcher.fireFileFinished(path);
    }
}

From source file:org.carrot2.output.metrics.PrecisionRecallMetric.java

public void calculate() {
    final int partitionCount = getPartitionsCount(documents);
    if (partitionCount == 0) {
        return;//ww w . java  2  s .c  o m
    }

    if (clusters.size() == 0) {
        return;
    }

    final SetMultimap<Object, Document> documentsByPartition = getDocumentsByPartition(documents);
    final Set<Object> partitions = getPartitions(documents);

    precisionByPartition = Maps.newHashMap();
    recallByPartition = Maps.newHashMap();
    fMeasureByPartition = Maps.newHashMap();

    double recallSum = 0;
    double precisionSum = 0;
    double fMeasureSum = 0;
    int partitionDocumentsCountSum = 0;

    for (Object partition : partitions) {
        final Set<Document> partitionDocuments = documentsByPartition.get(partition);
        final int partitionDocumentsCount = partitionDocuments.size();
        double partitionFMeasure = 0;
        double partitionPrecision = 0;
        double partitionRecall = 0;
        Cluster bestFMeasureCluster = null;

        for (Cluster cluster : clusters) {
            final List<Document> clusterDocuments = cluster.getAllDocuments();
            if (cluster.isOtherTopics() || clusterDocuments.size() == 0) {
                continue;
            }

            final Set<Document> commonDocuments = Sets.newHashSet(partitionDocuments);
            commonDocuments.retainAll(clusterDocuments);

            final double precision = commonDocuments.size() / (double) clusterDocuments.size();
            final double recall = commonDocuments.size() / (double) partitionDocumentsCount;
            final double fMeasure = MathUtils.harmonicMean(precision, recall);

            if (fMeasure > partitionFMeasure) {
                partitionFMeasure = fMeasure;
                partitionPrecision = precision;
                partitionRecall = recall;
                bestFMeasureCluster = cluster;
            }
        }

        recallSum += partitionRecall * partitionDocumentsCount;
        precisionSum += partitionPrecision * partitionDocumentsCount;
        fMeasureSum += partitionFMeasure * partitionDocumentsCount;
        partitionDocumentsCountSum += partitionDocumentsCount;

        recallByPartition.put(partition, partitionRecall);
        precisionByPartition.put(partition, partitionPrecision);
        fMeasureByPartition.put(partition, partitionFMeasure);
        if (bestFMeasureCluster != null) {
            bestFMeasureCluster.setAttribute(BEST_F_MEASURE_PARTITION, partition);
        }
    }

    // Dividing by partitionDocumentsCountSum rather than by the number of documents
    // because partitionDocumentsCountSum can be larger than the number of documents
    // if the partitions have overlapping documents.
    weightedAveragePrecision = precisionSum / partitionDocumentsCountSum;
    weightedAverageRecall = recallSum / partitionDocumentsCountSum;
    weightedAverageFMeasure = fMeasureSum / partitionDocumentsCountSum;
}