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.apache.aurora.scheduler.async.preemptor.PreemptorImpl.java

@Override
public synchronized Optional<String> findPreemptionSlotFor(final String taskId,
        AttributeAggregate attributeAggregate) {

    final Optional<IAssignedTask> pendingTask = fetchIdlePendingTask(taskId);

    // Task is no longer PENDING no need to preempt.
    if (!pendingTask.isPresent()) {
        return Optional.absent();
    }/*from ww w .j  a  v a2  s .c om*/

    Multimap<String, PreemptionVictim> slavesToActiveTasks = clusterState.getSlavesToActiveTasks();

    if (slavesToActiveTasks.isEmpty()) {
        return Optional.absent();
    }

    attemptedPreemptions.incrementAndGet();

    // Group the offers by slave id so they can be paired with active tasks from the same slave.
    Multimap<String, HostOffer> slavesToOffers = Multimaps.index(offerQueue.getOffers(), OFFER_TO_SLAVE_ID);

    Set<String> allSlaves = ImmutableSet.<String>builder().addAll(slavesToOffers.keySet())
            .addAll(slavesToActiveTasks.keySet()).build();

    for (String slaveID : allSlaves) {
        final Optional<Set<String>> toPreemptTasks = getTasksToPreempt(slavesToActiveTasks.get(slaveID),
                slavesToOffers.get(slaveID), pendingTask.get(), attributeAggregate);

        if (toPreemptTasks.isPresent()) {
            storage.write(new Storage.MutateWork.NoResult.Quiet() {
                @Override
                protected void execute(Storage.MutableStoreProvider storeProvider) {
                    for (String toPreempt : toPreemptTasks.get()) {
                        stateManager.changeState(storeProvider, toPreempt, Optional.<ScheduleStatus>absent(),
                                PREEMPTING, Optional.of("Preempting in favor of " + taskId));
                        tasksPreempted.incrementAndGet();
                    }
                }
            });
            return Optional.of(slaveID);
        }
    }

    noSlotsFound.incrementAndGet();
    return Optional.absent();
}

From source file:com.b2international.snowowl.snomed.validation.detail.SnomedValidationIssueDetailExtension.java

private void extendRelationshipIssueLabels(BranchContext context, Collection<ValidationIssue> issues) {
    final RevisionSearcher searcher = context.service(RevisionSearcher.class);

    final List<ValidationIssue> relationshipIssues = issues.stream()
            .filter(issue -> SnomedTerminologyComponentConstants.RELATIONSHIP_NUMBER == issue
                    .getAffectedComponent().getTerminologyComponentId())
            .collect(Collectors.toList());

    if (relationshipIssues.isEmpty()) {
        return;//from  ww  w .j ava 2  s .  c o m
    }

    final Multimap<String, ValidationIssue> issuesByRelationshipId = Multimaps.index(relationshipIssues,
            issue -> issue.getAffectedComponent().getComponentId());

    final Set<String> synonymIds = SnomedRequests.prepareGetSynonyms().build().execute(context).stream()
            .map(SnomedConcept::getId).collect(Collectors.toSet());

    final Set<String> conceptsToFetch = newHashSet();

    searcher.scroll(Query.select(String[].class).from(SnomedRelationshipIndexEntry.class)
            .fields(SnomedRelationshipIndexEntry.Fields.SOURCE_ID, SnomedRelationshipIndexEntry.Fields.TYPE_ID,
                    SnomedRelationshipIndexEntry.Fields.DESTINATION_ID)
            .where(SnomedRelationshipIndexEntry.Expressions.ids(issuesByRelationshipId.keySet()))
            .limit(SCROLL_SIZE).build()).forEach(hits -> {
                for (String[] hit : hits) {
                    conceptsToFetch.add(hit[0]);
                    conceptsToFetch.add(hit[1]);
                    conceptsToFetch.add(hit[2]);
                }
            });

    final Multimap<String, String> affectedComponentLabelsByConcept = HashMultimap.create();

    searcher.scroll(Query.select(String[].class).from(SnomedDescriptionIndexEntry.class)
            .fields(SnomedDescriptionIndexEntry.Fields.CONCEPT_ID, SnomedDescriptionIndexEntry.Fields.TERM)
            .where(Expressions.builder().filter(SnomedDescriptionIndexEntry.Expressions.active())
                    .filter(SnomedDescriptionIndexEntry.Expressions.concepts(conceptsToFetch))
                    .filter(SnomedDescriptionIndexEntry.Expressions.types(ImmutableSet.<String>builder()
                            .add(Concepts.FULLY_SPECIFIED_NAME).addAll(synonymIds).build()))
                    .build())
            .limit(SCROLL_SIZE).build()).forEach(hits -> {
                for (String[] hit : hits) {
                    affectedComponentLabelsByConcept.put(hit[0], hit[1]);
                }
            });

    if (!affectedComponentLabelsByConcept.isEmpty()) {
        issuesByRelationshipId.values().forEach(issue -> {
            final Collection<String> labels = affectedComponentLabelsByConcept
                    .get(issue.getAffectedComponent().getComponentId());
            issue.setAffectedComponentLabels(ImmutableList.copyOf(labels));
        });
    }
}

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

/**
 * TODO IMPROVE   //  w w  w .  j av  a 2s  .c om
 * @return 
 */
public Map<String, Integer> getFullBetCount() {

    // transform BaseGame into string description
    Function<BaseGame, String> gameToStringFunction = new Function<BaseGame, String>() {

        @Override
        public String apply(final BaseGame baseGame) {
            if (baseGame instanceof StandardBaseGame) {
                return "Standard";
            } else if (baseGame instanceof BelgianBaseGame) {
                return "Belge";
            } else if (baseGame instanceof PassedGame) {
                return "Passe";
            } else if (baseGame instanceof PenaltyGame) {
                return "Fausse donne";
            } else {
                throw new IllegalArgumentException("GetFullBetCount() Unknow game type");
            }

        }
    };

    // group games by string description 
    ImmutableListMultimap<String, BaseGame> descriptionMultimap = Multimaps.index(this.gameSet.getGames(),
            gameToStringFunction);

    // build return object
    Map<String, Integer> toReturn = newHashMap();
    for (String description : descriptionMultimap.keys()) {
        toReturn.put(description, descriptionMultimap.get(description).size());
    }
    this.fullBetSeriesCount = toReturn.keySet().size();

    return toReturn;
}

From source file:com.b2international.snowowl.snomed.datastore.converter.SnomedConceptConverter.java

private void expandDescriptions(List<SnomedConcept> results, final Set<String> conceptIds) {
    if (!expand().containsKey(SnomedConcept.Expand.DESCRIPTIONS)) {
        return;//w  w  w . j  a va2 s  . co m
    }

    final Options expandOptions = expand().get(SnomedConcept.Expand.DESCRIPTIONS, Options.class);
    final SnomedDescriptions descriptions = SnomedRequests.prepareSearchDescription().all()
            .setExpand(expandOptions.get("expand", Options.class))
            .filterByType(expandOptions.containsKey("typeId") ? expandOptions.getString("typeId") : null)
            .filterByConceptId(conceptIds).setLocales(locales()).build().execute(context());

    final ListMultimap<String, SnomedDescription> descriptionsByConceptId = Multimaps.index(descriptions,
            description -> description.getConceptId());

    for (SnomedConcept concept : results) {
        final List<SnomedDescription> conceptDescriptions = descriptionsByConceptId.get(concept.getId());
        concept.setDescriptions(new SnomedDescriptions(conceptDescriptions, null, null,
                conceptDescriptions.size(), conceptDescriptions.size()));
    }
}

From source file:org.icgc.dcc.portal.manifest.ManifestService.java

private void eachRepository(ManifestContext context, SearchResponse searchResult, BundlesCallback callback)
        throws IOException {
    // Map and filter
    Stream<ManifestFile> files = new ManifestMapper(repositories.findAll()).map(searchResult)
            .filter(file -> context.isActive(file.getRepoCode()));

    if (context.getManifest().isUnique()) {
        // Remove duplicates by file id by choosing the one with the higest priority
        files = files/*from www. j  ava 2s. c  o  m*/
                .sorted(fileIdOrder().thenComparing(priorityFileCopyOrder(context.getManifest().getRepos())))
                .filter(distinctByKey(file -> file.getId()));
    }

    // Group files from each repo together
    val repoCodeFiles = files.collect(groupingBy(file -> file.getRepoCode()));

    // Iterate in order of priority
    for (val repoCode : prioritizeRepoCodes(context.getManifest().getRepos(), repoCodeFiles.keySet())) {
        val repo = repositories.findOne(repoCode);
        val repoFiles = repoCodeFiles.get(repoCode);

        // Index
        val bundles = Multimaps.index(repoFiles, file -> formatFileURL(repo, file));

        // Hand off
        callback.handle(repo, bundles);
    }
}

From source file:com.google.javascript.jscomp.deps.DepsGenerator.java

/**
 * Creates the content to put into the output deps.js file. If mergeDeps is
 * true, then all of the dependency information in the providedDeps will be
 * included in the output.// www.  ja  v  a  2 s . c om
 * @throws IOException Occurs upon an IO error.
 */
private void writeDepsContent(Map<String, DependencyInfo> depsFiles, Map<String, DependencyInfo> jsFiles,
        PrintStream out) throws IOException {
    // Print all dependencies extracted from srcs.
    writeDepInfos(out, jsFiles.values());

    // Print all dependencies extracted from deps.
    if (mergeStrategy == InclusionStrategy.ALWAYS) {
        // This multimap is just for splitting DepsInfo objects by
        // it's definition deps.js file
        Multimap<String, DependencyInfo> infosIndex = Multimaps.index(depsFiles.values(),
                new Function<DependencyInfo, String>() {
                    @Override
                    public String apply(DependencyInfo from) {
                        return from.getName();
                    }
                });

        for (String depsPath : infosIndex.keySet()) {
            String path = formatPathToDepsFile(depsPath);
            out.println("\n// Included from: " + path);
            writeDepInfos(out, infosIndex.get(depsPath));
        }
    }
}

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

private void updatePrimaryWellConcentration(Plate plate) {
    Map<String, Object> properties = Maps.newHashMap();
    properties.put("plateNumber", plate.getPlateNumber());
    properties.put("libraryWellType", LibraryWellType.EXPERIMENTAL);
    List<Well> wells = _dao.findEntitiesByProperties(Well.class, properties);
    ConcentrationStatistics concentrationStatistics = plate.getConcentrationStatistics();
    for (Well well : wells) {
        if (well.getMgMlConcentration() != null) {
            if (concentrationStatistics.getMaxMgMlConcentration() == null)
                concentrationStatistics.setMaxMgMlConcentration(well.getMgMlConcentration());
            else if (well.getMgMlConcentration()
                    .compareTo(concentrationStatistics.getMaxMgMlConcentration()) > 0)
                concentrationStatistics.setMaxMgMlConcentration(well.getMgMlConcentration());
            if (concentrationStatistics.getMinMgMlConcentration() == null)
                concentrationStatistics.setMinMgMlConcentration(well.getMgMlConcentration());
            else if (well.getMgMlConcentration()
                    .compareTo(concentrationStatistics.getMinMgMlConcentration()) < 0)
                concentrationStatistics.setMinMgMlConcentration(well.getMgMlConcentration());
        }//from   w  w  w .jav a2s.  c o  m
        if (well.getMolarConcentration() != null) {
            if (concentrationStatistics.getMaxMolarConcentration() == null)
                concentrationStatistics.setMaxMolarConcentration(well.getMolarConcentration());
            else if (well.getMolarConcentration()
                    .compareTo(concentrationStatistics.getMaxMolarConcentration()) > 0)
                concentrationStatistics.setMaxMolarConcentration(well.getMolarConcentration());
            if (concentrationStatistics.getMinMolarConcentration() == null)
                concentrationStatistics.setMinMolarConcentration(well.getMolarConcentration());
            else if (well.getMolarConcentration()
                    .compareTo(concentrationStatistics.getMinMolarConcentration()) < 0)
                concentrationStatistics.setMinMolarConcentration(well.getMolarConcentration());
        }
    }

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

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

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

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

From source file:edu.isi.karma.modeling.alignment.SemanticModel.java

private List<HashMap<Node, String>> getPossibleNodeIdSets() {

    DirectedWeightedMultigraph<Node, LabeledLink> g = this.getGraph();
    List<HashMap<Node, String>> nodeIdSets = new ArrayList<>();
    if (g == null)
        return nodeIdSets;

    Set<Node> internalNodes = new HashSet<>();
    for (Node n : g.vertexSet())
        if (n instanceof InternalNode)
            internalNodes.add(n);// w  ww  . j a  v  a2 s  .co m

    Set<Node> columnNodes = new HashSet<>();
    for (Node n : g.vertexSet())
        if (n instanceof ColumnNode)
            columnNodes.add(n);

    Function<Node, String> sameUriNodes = new Function<Node, String>() {
        @Override
        public String apply(final Node n) {
            if (n == null || n.getLabel() == null)
                return null;
            return n.getLabel().getUri();
        }
    };

    Multimap<String, Node> index = Multimaps.index(internalNodes, sameUriNodes);
    int numberOfPossibleSets = 1;
    for (String s : index.keySet()) {
        Collection<Node> nodeGroup = index.get(s);
        if (nodeGroup != null && !nodeGroup.isEmpty()) {
            numberOfPossibleSets *= BigIntegerMath.factorial(nodeGroup.size()).intValue();
        }
    }
    //      System.out.println(numberOfPossibleSets);

    for (int i = 0; i < numberOfPossibleSets; i++) {
        HashMap<Node, String> nodeIds = new HashMap<>();
        NodeIdFactory nodeIdFactory = new NodeIdFactory();

        for (Node n : columnNodes) {
            ColumnNode cn;
            if (this.mappingToSourceColumns != null
                    && (cn = this.mappingToSourceColumns.get((ColumnNode) n)) != null) {
                nodeIds.put(n, cn.getId());
            } else {
                nodeIds.put(n, n.getId());
            }
        }

        for (String s : index.keySet()) {
            Collection<Node> nodeGroup = index.get(s);
            if (nodeGroup != null && nodeGroup.size() == 1) {
                Node n = nodeGroup.iterator().next();
                nodeIds.put(n, nodeIdFactory.getNodeId(n.getLabel().getUri()));
            }
        }

        nodeIdSets.add(nodeIds);
    }

    //      List<Node> nodes = new ArrayList<Node>();
    //      List<Set<String>> idList = new ArrayList<Set<String>>(); 
    //      Set<List<String>> idProductSets = null;
    //      NodeIdFactory nodeIdFactory = new NodeIdFactory();
    //      for (String s : index.keySet()) {
    //         Collection<Node> nodeGroup = index.get(s);
    //         if (nodeGroup == null)
    //            continue;
    //         nodes.addAll(nodeGroup);
    //         Set<String> ids = new TreeSet<String>();
    //         for (Node n : nodeGroup) {
    //            ids.add(nodeIdFactory.getNodeId(n.getLabel().getUri()));
    //         }
    //         idList.add(ids);
    //         
    //      }
    //      if (idList != null)
    //         idProductSets = Sets.cartesianProduct(idList);
    //      
    //      int i = 0;
    //      for (List<String> ids : idProductSets) {
    //         for (Node n : nodes) System.out.println("node: " + n.getLabel().getUri());
    //         for (String id : ids) System.out.println("id: " + id);
    //
    //         for (int j = 0; j < ids.size() && j < nodes.size(); j++)
    //            nodeIdSets.get(i).put(nodes.get(j), ids.get(j));
    //         i++;
    //      }

    int interval = numberOfPossibleSets;
    NodeIdFactory nodeIdFactory = new NodeIdFactory();
    for (String s : index.keySet()) {
        Collection<Node> nodeGroup = index.get(s);
        if (nodeGroup != null && nodeGroup.size() > 1) {
            Set<String> ids = new HashSet<>();
            List<Node> nodes = new ArrayList<>();
            nodes.addAll(nodeGroup);
            for (Node n : nodes)
                ids.add(nodeIdFactory.getNodeId(n.getLabel().getUri()));

            Collection<List<String>> permutations = Collections2.permutations(ids);
            List<List<String>> permList = new ArrayList<>();
            permList.addAll(permutations);

            interval = interval / BigIntegerMath.factorial(nodeGroup.size()).intValue();
            List<String> perm;
            int k = 0, count = 1;
            for (int i = 0; i < nodeIdSets.size(); i++) {
                HashMap<Node, String> nodeIds = nodeIdSets.get(i);
                if (count > interval) {
                    k = ++k % permList.size();
                    count = 1;
                }
                perm = permList.get(k);
                for (int j = 0; j < nodes.size(); j++)
                    nodeIds.put(nodes.get(j), perm.get(j));
                count++;
            }
        }
    }

    return nodeIdSets;
}

From source file:org.calrissian.mango.collect.FluentCloseableIterable.java

/**
 * Creates an index {@code ImmutableListMultimap} that contains the results of applying a
 * specified function to each item in this {@code FluentIterable} of values. Each element of this
 * iterable will be stored as a value in the resulting multimap, yielding a multimap with the same
 * size as this iterable. The key used to store that value in the multimap will be the result of
 * calling the function on that value. The resulting multimap is created as an immutable snapshot.
 * In the returned multimap, keys appear in the order they are first encountered, and the values
 * corresponding to each key appear in the same order as they are encountered.
 *
 * @param keyFunction the function used to produce the key for each value
 * @throws NullPointerException if any of the following cases is true:
 *     <ul>/*from   w  ww  .j  ava2  s. co m*/
 *       <li>{@code keyFunction} is null
 *       <li>An element in this fluent iterable is null
 *       <li>{@code keyFunction} returns {@code null} for any element of this iterable
 *     </ul>
 */
public final <K> ImmutableListMultimap<K, T> index(Function<? super T, K> keyFunction) {
    return Multimaps.index(this, keyFunction);
}

From source file:org.geogit.api.plumbing.diff.DiffTreeVisitor.java

/**
 * Split the given nodes into lists keyed by the bucket indes they would belong if they were
 * part of a tree bucket at the given {@code bucketDepth}
 *//*from   ww  w  .  j a va 2 s  .  c o m*/
private ListMultimap<Integer, Node> splitNodesToBucketsAtDepth(Iterator<Node> nodes, final int bucketDepth) {

    Function<Node, Integer> keyFunction = new Function<Node, Integer>() {
        @Override
        public Integer apply(Node node) {
            return ORDER.bucket(node, bucketDepth);
        }
    };
    ListMultimap<Integer, Node> nodesByBucket = Multimaps.index(nodes, keyFunction);
    return nodesByBucket;
}