Example usage for com.google.common.collect Multimaps index

List of usage examples for com.google.common.collect Multimaps index

Introduction

In this page you can find the example usage for com.google.common.collect Multimaps index.

Prototype

public static <K, V> ImmutableListMultimap<K, V> index(Iterator<V> values, Function<? super V, K> keyFunction) 

Source Link

Document

Creates an index ImmutableListMultimap that contains the results of applying a specified function to each item in an Iterator of values.

Usage

From source file:org.carrot2.text.clustering.MultilingualClustering.java

/**
 * Clusters documents in each language separately.
 *//*from ww w .  ja v a2  s. c  om*/
private Map<LanguageCode, Cluster> clusterByLanguage(List<Document> documents,
        IMonolingualClusteringAlgorithm algorithm) {
    // Partition by language first. As Multimaps.index() does not handle null
    // keys, we'd need to index by LanguageCode string and have a dedicated empty
    // string for the null language.
    final ImmutableListMultimap<String, Document> documentsByLanguage = Multimaps.index(documents,
            new Function<Document, String>() {
                public String apply(Document document) {
                    final LanguageCode language = document.getLanguage();
                    return language != null ? language.name() : "";
                }
            });

    // For each language, perform clustering. Please note that implementations of 
    // IMonolingualClusteringAlgorithm.cluster() are not guaranteed to be thread-safe
    // and hence the method must NOT be called concurrently.
    final Map<LanguageCode, Cluster> clusters = Maps.newHashMap();
    for (String language : documentsByLanguage.keySet()) {
        final ImmutableList<Document> languageDocuments = documentsByLanguage.get(language);
        final LanguageCode languageCode = language.equals("") ? null : LanguageCode.valueOf(language);
        final Cluster languageCluster = new Cluster(
                languageCode != null ? languageCode.toString() : "Unknown Language");

        languageCounts.put(languageCode != null ? languageCode.getIsoCode() : "", languageDocuments.size());

        // Perform clustering
        final LanguageCode currentLanguage = languageCode != null ? languageCode : defaultLanguage;
        logger.debug("Performing monolingual clustering in: " + currentLanguage);
        final List<Cluster> clustersForLanguage = algorithm.process(languageDocuments, currentLanguage);

        if (clustersForLanguage.size() == 0
                || clustersForLanguage.size() == 1 && clustersForLanguage.get(0).isOtherTopics()) {
            languageCluster.addDocuments(languageDocuments);
        } else {
            languageCluster.addSubclusters(clustersForLanguage);
        }

        clusters.put(languageCode, languageCluster);
    }

    return clusters;
}

From source file:org.nla.tarotdroid.biz.computers.GuavaGameSetStatisticsComputer.java

/**
 * Returns for each player the number of games he has been called.   
 * @return for each player the number of games he has been called as a Map<Player, Integer>.
 *///w ww  .j av a 2s  .  com
public Map<Player, Integer> getCalledCount() {
    // transform StandardBaseGame into Player
    Function<StandardTarot5Game, Player> gameSetToCalledPlayerFunction = new Function<StandardTarot5Game, Player>() {

        @Override
        public Player apply(final StandardTarot5Game stdBaseGame) {
            return stdBaseGame.getCalledPlayer();
        }
    };

    // group standard games by player 
    ImmutableListMultimap<Player, StandardTarot5Game> calledPlayerMultimap = Multimaps
            .index(this.gameSet.getStandard5Games(), gameSetToCalledPlayerFunction);

    // build return object
    Map<Player, Integer> toReturn = newHashMap();
    for (Player player : calledPlayerMultimap.keys()) {
        toReturn.put(player, calledPlayerMultimap.get(player).size());
    }
    this.calledPlayerSeriesCount = toReturn.keySet().size();

    return toReturn;
}

From source file:com.google.errorprone.bugpatterns.ModifyingCollectionWithItself.java

private Multimap<Integer, JCVariableDecl> partitionByEditDistance(final String baseName,
        Iterable<JCVariableDecl> candidates) {
    return Multimaps.index(candidates, new Function<JCVariableDecl, Integer>() {
        @Override//  w ww . java2s  .co m
        public Integer apply(JCVariableDecl jcVariableDecl) {
            return EditDistance.getEditDistance(baseName, jcVariableDecl.name.toString());
        }
    });
}

From source file:org.apache.aurora.scheduler.thrift.ReadOnlySchedulerImpl.java

@Override
public Response getRoleSummary() {
    Multimap<String, IJobKey> jobsByRole = storage.read(
            storeProvider -> Multimaps.index(storeProvider.getTaskStore().getJobKeys(), IJobKey::getRole));

    Multimap<String, IJobKey> cronJobsByRole = Multimaps.index(
            Iterables.transform(Storage.Util.fetchCronJobs(storage), IJobConfiguration::getKey),
            IJobKey::getRole);/* w ww .j  a v a 2 s .c o m*/

    Set<RoleSummary> summaries = FluentIterable.from(Sets.union(jobsByRole.keySet(), cronJobsByRole.keySet()))
            .transform(
                    role -> new RoleSummary(role, jobsByRole.get(role).size(), cronJobsByRole.get(role).size()))
            .toSet();

    return ok(Result.roleSummaryResult(new RoleSummaryResult(summaries)));
}

From source file:org.opentestsystem.authoring.testauth.publish.SharedPublisherHelper.java

private List<TestComputationRule> buildTestComputationRulesForLeafNodeRules(
        final List<ScoringRule> scoringRuleList, final List<BlueprintElement> blueprintElementList) {
    final List<TestComputationRule> testComputationRuleList = Lists.newArrayList();
    if (Iterables.any(scoringRuleList, LEAF_NODE_TYPE_FILTER)) {
        // winnow blueprintElement list down to parentedChildren only
        Iterables.removeIf(blueprintElementList, PARENT_KEY_FILTER);
        // build multimap of bpe keyed by parent key
        final Multimap<String, BlueprintElement> blueprintElementParentKeyMultimap = Multimaps
                .index(blueprintElementList, BP_PARENT_KEY_TRANSFORMER);

        // filter bpe objects that are parents from parentedChildren
        Iterables.removeIf(blueprintElementList,
                NON_LEAF_NODE_FILTER.getInstance(blueprintElementParentKeyMultimap.keySet()));

        // construct each leaf node into a separate scoring rule
        final List<ScoringRule> leafNodeScoringRules = Lists
                .newArrayList(Iterables.filter(scoringRuleList, LEAF_NODE_TYPE_FILTER));
        for (final ScoringRule scoringRule : leafNodeScoringRules) {
            final int i = 1;
            // transform every leaf node bp element into a scoring rule mimicking this scoringRule
            testComputationRuleList.addAll(Lists.transform(blueprintElementList,
                    LEAF_NODE_LEVEL_SCORING_RULE_TRANSFORMER.getInstance(scoringRule, i)));
        }//w  w  w .  j  ava  2 s  .  c  o  m
    }
    return testComputationRuleList;
}

From source file:org.sosy_lab.cpachecker.core.algorithm.pdr.transition.BackwardTransition.java

public FluentIterable<Block> getBlocksTo(Iterable<CFANode> pSuccessorLocations,
        Predicate<AbstractState> pFilterPredecessors) throws CPAException, InterruptedException {

    Map<CFANode, Iterable<Block>> cached = cache.getAllPresent(pSuccessorLocations);

    Iterable<CFANode> uncachedSuccessorLocations = Iterables.filter(pSuccessorLocations,
            node -> !cached.containsKey(node));
    Iterator<CFANode> successorLocationIterator = uncachedSuccessorLocations.iterator();
    if (!successorLocationIterator.hasNext()) {
        return FluentIterable.from(Collections.emptyList());
    }//from  w  ww  .j  a  va  2  s.c  o m
    ReachedSet reachedSet;
    // If there is only one successor location,
    // the initial state is unambiguous and can be created with less effort
    CFANode firstSuccessorLocation = successorLocationIterator.next();
    if (!successorLocationIterator.hasNext()) {
        return getBlocksTo(firstSuccessorLocation).filter(Blocks.applyToPredecessor(pFilterPredecessors));
    }
    reachedSet = reachedSetFactory.create();
    initializeFor(reachedSet, firstSuccessorLocation);
    while (successorLocationIterator.hasNext()) {
        CFANode successorLocation = successorLocationIterator.next();
        initializeFor(reachedSet, successorLocation);
    }

    Set<AbstractState> allInitialStates = FluentIterable.from(reachedSet).toSet();

    algorithm.run(reachedSet);
    Function<ARGState, AbstractState> asAbstractState = asAbstractState(reachedSet);

    Set<Block> computedBlocks = FluentIterable.from(reachedSet)
            // Only consider abstract states where a block starts
            .filter(IS_BLOCK_START)
            // Apply the client-provided filter
            .filter(pFilterPredecessors)
            .transformAndConcat((blockStartState) -> FluentIterable
                    .from(getInitialStates(blockStartState, allInitialStates, asAbstractState))
                    .transform((initialState) -> (Block) new BlockImpl(initialState, blockStartState,
                            AnalysisDirection.BACKWARD,
                            getReachedSet(initialState, blockStartState, reachedSet, asAbstractState))))
            .toSet();

    for (Map.Entry<CFANode, Collection<Block>> entry : Multimaps
            .index(computedBlocks, block -> block.getSuccessorLocation()).asMap().entrySet()) {
        cache.put(entry.getKey(), entry.getValue());
        assert !cached.keySet().contains(entry.getKey());
    }

    return FluentIterable.from(Iterables.concat(Iterables.concat(cached.values()), computedBlocks));
}

From source file:edu.harvard.med.screensaver.service.libraries.PlateUpdater.java

@Transactional
public void updatePrimaryPlateConcentrations(Copy copy) {
    ConcentrationStatistics concentrationStatistics = new ConcentrationStatistics();
    copy.setConcentrationStatistics(concentrationStatistics);
    // update the plates using values from the wells
    Collection<Plate> platesToConsider = Sets.newHashSet(copy.getPlates().values());

    for (Iterator<Plate> iter = platesToConsider.iterator(); iter.hasNext();) {
        Plate p = iter.next();/*from  w  w  w . j  ava 2  s .  com*/
        p.setConcentrationStatistics(new ConcentrationStatistics());
        updatePrimaryWellConcentration(p);
        // update the copy with the values from the plate
        if (p.getMaxMgMlConcentration() != null) {
            if (concentrationStatistics.getMaxMgMlConcentration() == null)
                concentrationStatistics.setMaxMgMlConcentration(p.getMaxMgMlConcentration());
            else if (p.getMaxMgMlConcentration()
                    .compareTo(concentrationStatistics.getMaxMgMlConcentration()) > 0)
                concentrationStatistics.setMaxMgMlConcentration(p.getMaxMgMlConcentration());
            if (concentrationStatistics.getMinMgMlConcentration() == null)
                concentrationStatistics.setMinMgMlConcentration(p.getMinMgMlConcentration());
            else if (p.getMinMgMlConcentration()
                    .compareTo(concentrationStatistics.getMinMgMlConcentration()) < 0)
                concentrationStatistics.setMinMgMlConcentration(p.getMinMgMlConcentration());
        }
        if (p.getMaxMolarConcentration() != null) {
            if (concentrationStatistics.getMaxMolarConcentration() == null)
                concentrationStatistics.setMaxMolarConcentration(p.getMaxMolarConcentration());
            else if (p.getMaxMolarConcentration()
                    .compareTo(concentrationStatistics.getMaxMolarConcentration()) > 0)
                concentrationStatistics.setMaxMolarConcentration(p.getMaxMolarConcentration());
            if (concentrationStatistics.getMinMolarConcentration() == null)
                concentrationStatistics.setMinMolarConcentration(p.getMinMolarConcentration());
            else if (p.getMinMolarConcentration()
                    .compareTo(concentrationStatistics.getMinMolarConcentration()) < 0)
                concentrationStatistics.setMinMolarConcentration(p.getMinMolarConcentration());
        }
        if (!isStoredAtFacility.apply(p.getStatus())) // consider only plates stored at this facility
        {
            iter.remove();
            continue;
        }
    }

    Map<BigDecimal, Integer> mgMlCounts = Maps
            .transformValues(
                    Multimaps.index(
                            Lists.newArrayList(Iterators.filter(platesToConsider.iterator(),
                                    Predicates.compose(Predicates.notNull(),
                                            Plate.ToPrimaryWellMgMlConcentration))),
                            Plate.ToPrimaryWellMgMlConcentration).asMap(),
                    CollectionSize);

    if (!mgMlCounts.isEmpty())
        concentrationStatistics.setPrimaryWellMgMlConcentration(findMaxByValueThenKey(mgMlCounts).getKey());

    Map<MolarConcentration, Integer> molarCounts = Maps
            .transformValues(
                    Multimaps.index(
                            Lists.newArrayList(Iterators.filter(platesToConsider.iterator(),
                                    Predicates.compose(Predicates.notNull(),
                                            Plate.ToPrimaryWellMolarConcentration))),
                            Plate.ToPrimaryWellMolarConcentration).asMap(),
                    CollectionSize);

    if (!molarCounts.isEmpty())
        concentrationStatistics.setPrimaryWellMolarConcentration(findMaxByValueThenKey(molarCounts).getKey());
}

From source file:org.obiba.opal.web.gwt.app.client.magma.view.SummaryTabView.java

private void renderGeoSummary(SummaryStatisticsDto dto) {
    GeoSummaryDto geoSummaryDto = dto.getExtension(GeoSummaryDto.SummaryStatisticsDtoExtensions.geoSummary)
            .cast();// w w  w.  ja  va2s . com

    final double[] totals = { 0d, 0d };
    ImmutableListMultimap<Boolean, FrequencyDto> valuesByMissing = Multimaps.index(
            JsArrays.toIterable(geoSummaryDto.getFrequenciesArray()), new Function<FrequencyDto, Boolean>() {
                @Nullable
                @Override
                public Boolean apply(@Nullable FrequencyDto input) {
                    if (input != null && !input.getMissing()) {
                        input.setValue(translations.notEmpty());
                        totals[0] += input.getFreq();
                        return false;
                    }
                    totals[1] += input == null ? 0 : input.getFreq();
                    return true;
                }
            });

    summary.add(new GeoSummaryView(geoSummaryDto, valuesByMissing.get(false), valuesByMissing.get(true),
            totals[0], totals[1]));
}

From source file:org.obm.imap.archive.services.MailboxProcessing.java

private Map<Year, MessageSet> mapByYear(Mailbox mailbox, MessageSet messageSet)
        throws ImapSelectException, MailboxNotFoundException {
    if (messageSet.isEmpty()) {
        return ImmutableMap.of();
    }/*  w  w w  . j av a 2 s.c  o m*/

    mailbox.select();
    Year year = guessRangeYear(mailbox, messageSet);
    MessageSet otherYears = searchOutOfYearMessages(mailbox, messageSet, year);

    HashMap<Year, MessageSet> messageSetsByYear = Maps.newHashMap(Maps.transformValues(
            Multimaps.index(mailbox.fetchInternalDate(otherYears), new YearFromInternalDate()).asMap(),
            new CreateMessageSet<>()));
    messageSetsByYear.put(year, messageSet.remove(otherYears));
    return messageSetsByYear;
}

From source file:org.apache.solr.search.ExtendedDismaxQParser.java

/**
 * Adds shingled phrase queries to all the fields specified in the pf, pf2 anf pf3 parameters
 * //from   ww  w .j  a va 2  s .co  m
 */
protected void addPhraseFieldQueries(BooleanQuery.Builder query, List<Clause> clauses,
        ExtendedDismaxConfiguration config) throws SyntaxError {

    // sloppy phrase queries for proximity
    List<FieldParams> allPhraseFields = config.getAllPhraseFields();

    if (allPhraseFields.size() > 0) {
        // find non-field clauses
        List<Clause> normalClauses = new ArrayList<>(clauses.size());
        for (Clause clause : clauses) {
            if (clause.field != null || clause.isPhrase)
                continue;
            // check for keywords "AND,OR,TO"
            if (clause.isBareWord()) {
                String s = clause.val;
                // avoid putting explicit operators in the phrase query
                if ("OR".equals(s) || "AND".equals(s) || "NOT".equals(s) || "TO".equals(s))
                    continue;
            }
            normalClauses.add(clause);
        }

        // create a map of {wordGram, [phraseField]}
        Multimap<Integer, FieldParams> phraseFieldsByWordGram = Multimaps.index(allPhraseFields,
                FieldParams::getWordGrams);

        // for each {wordGram, [phraseField]} entry, create and add shingled field queries to the main user query
        for (Map.Entry<Integer, Collection<FieldParams>> phraseFieldsByWordGramEntry : phraseFieldsByWordGram
                .asMap().entrySet()) {

            // group the fields within this wordGram collection by their associated slop (it's possible that the same
            // field appears multiple times for the same wordGram count but with different slop values. In this case, we
            // should take the *sum* of those phrase queries, rather than the max across them).
            Multimap<Integer, FieldParams> phraseFieldsBySlop = Multimaps
                    .index(phraseFieldsByWordGramEntry.getValue(), FieldParams::getSlop);
            for (Map.Entry<Integer, Collection<FieldParams>> phraseFieldsBySlopEntry : phraseFieldsBySlop
                    .asMap().entrySet()) {
                addShingledPhraseQueries(query, normalClauses, phraseFieldsBySlopEntry.getValue(),
                        phraseFieldsByWordGramEntry.getKey(), config.tiebreaker,
                        phraseFieldsBySlopEntry.getKey());
            }
        }
    }
}