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:com.b2international.snowowl.snomed.validation.detail.SnomedValidationIssueDetailExtension.java

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

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

    if (conceptIssues.isEmpty()) {
        return;//  w  ww  .j  ava2 s. com
    }

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

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

    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(issuesByConceptId.keySet()))
                    .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()) {
        issuesByConceptId.values().forEach(issue -> {
            final Collection<String> labels = affectedComponentLabelsByConcept
                    .get(issue.getAffectedComponent().getComponentId());
            issue.setAffectedComponentLabels(ImmutableList.copyOf(labels));
        });
    }
}

From source file:edu.mit.streamjit.impl.compiler2.ActorArchetype.java

public void generateCode(String packageName, ModuleClassLoader loader, Iterable<WorkerActor> actors) {
    assert workMethods == null : "already generated code for " + this;
    //If we've removed all instances of this archetype, don't spin an empty class.
    if (Iterables.isEmpty(actors))
        return;// w  w  w.j  av  a2  s .c o m

    Module module = workerKlass.getParent();
    TypeFactory types = module.types();
    //We need to resolve work before making the state holder class so we
    //pick up its uses.
    Method oldWork = workerKlass.getMethodByVirtual("work",
            types.getMethodType(types.getVoidType(), types.getRegularType(workerKlass)));
    oldWork.resolve();

    Klass stateHolderKlass = makeStateHolderKlass(packageName);
    Klass archetypeKlass = new Klass(packageName + "." + workerKlass.getName() + "Archetype",
            module.getKlass(Object.class), ImmutableList.<Klass>of(), module);
    archetypeKlass.modifiers().addAll(EnumSet.of(Modifier.PUBLIC, Modifier.FINAL));

    Map<Pair<Class<?>, Class<?>>, Method> methods = new HashMap<>();
    for (WorkerActor a : actors) {
        Class<?> inputType = a.inputType().getRawType(), outputType = a.outputType().getRawType();
        Pair<Class<?>, Class<?>> key = new Pair<Class<?>, Class<?>>(inputType, outputType);
        if (methods.containsKey(key))
            continue;

        //We modify rwork while remapping so we need a fresh clone.
        Method rwork = makeRwork(archetypeKlass, stateHolderKlass);
        for (BasicBlock b : rwork.basicBlocks())
            for (Instruction i : ImmutableList.copyOf(b.instructions()))
                if (i.operands().contains(rwork.arguments().get(0)) ||
                //TODO: also check for superclass fields
                        i.operands().anyMatch(Predicates.<Value>in(workerKlass.fields())))
                    remapEliminatingReceiver(i, inputType, outputType, stateHolderKlass);

        assert rwork.arguments().get(0).uses().isEmpty();
        Method work = new Method(makeWorkMethodName(inputType, outputType), rwork.getType().dropFirstArgument(),
                EnumSet.of(Modifier.PUBLIC, Modifier.STATIC), archetypeKlass);
        Map<Value, Value> vmap = new IdentityHashMap<>();
        vmap.put(rwork.arguments().get(0), null);
        for (int i = 1; i < rwork.arguments().size(); ++i)
            vmap.put(rwork.arguments().get(i), work.arguments().get(i - 1));
        Cloning.cloneMethod(rwork, work, vmap);
        cleanWorkMethod(work);
        methods.put(key, work);
        rwork.eraseFromParent();
    }

    ImmutableMap.Builder<Pair<Class<?>, Class<?>>, MethodHandle> workMethodsBuilder = ImmutableMap.builder();
    try {
        Class<?> stateHolderClass = loader.loadClass(stateHolderKlass.getName());
        this.constructStateHolder = findConstructor(stateHolderClass);
        Class<?> archetypeClass = loader.loadClass(archetypeKlass.getName());
        ImmutableListMultimap<String, java.lang.reflect.Method> methodsByName = Multimaps
                .index(Arrays.asList(archetypeClass.getMethods()), java.lang.reflect.Method::getName);
        for (Pair<Class<?>, Class<?>> p : methods.keySet()) {
            String name = makeWorkMethodName(p.first, p.second);
            workMethodsBuilder.put(p,
                    MethodHandles.publicLookup().unreflect(Iterables.getOnlyElement(methodsByName.get(name))));
        }
    } catch (ClassNotFoundException | IllegalAccessException ex) {
        throw new AssertionError(ex);
    }
    this.workMethods = workMethodsBuilder.build();
}

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

/**
 * Returns for each bet the number of games this bet has been called.   
 * @return for each bet the number of games this bet has been called as a Map<BetType, Double>.
 *///from  ww w .ja v  a  2  s  .  c o m
public Map<BetType, Integer> getBetCount() {

    // transform StandardBaseGame into BetType
    Function<StandardBaseGame, BetType> gameToBetTypeFunction = new Function<StandardBaseGame, BetType>() {

        @Override
        public BetType apply(final StandardBaseGame stdBaseGame) {
            return stdBaseGame.getBet().getBetType();
        }
    };

    // group standard games by bet type 
    ImmutableListMultimap<BetType, StandardBaseGame> betTypeMultimap = Multimaps
            .index(this.gameSet.getStandardGames(), gameToBetTypeFunction);

    // build return object
    Map<BetType, Integer> toReturn = newHashMap();
    for (BetType betType : betTypeMultimap.keys()) {
        toReturn.put(betType, betTypeMultimap.get(betType).size());
    }
    this.betSeriesCount = toReturn.keySet().size();

    return toReturn;
}

From source file:org.icgc.dcc.release.job.annotate.converter.SnpEffVCFToICGCConverter.java

/**
 * Groups {@code effects} by transcript or by gene affected if transcript is unavailable.
 *//*from w w w .j  av  a2s. co  m*/
private static Multimap<String, SnpEffect> groupEffects(Collection<SnpEffect> effects) {
    Multimap<String, SnpEffect> transcriptIdMap = Multimaps.index(effects, new Function<SnpEffect, String>() {

        @Override
        public String apply(@NonNull SnpEffect item) {
            return !item.getTranscriptID().isEmpty() ? item.getTranscriptID() : item.getGeneName();
        }

    });

    return transcriptIdMap;
}

From source file:dagger.internal.codegen.BindingGraphFactory.java

/** Indexes {@code bindingDeclarations} by {@link BindingDeclaration#key()}. */
private static <T extends BindingDeclaration> ImmutableSetMultimap<Key, T> indexBindingDeclarationsByKey(
        Iterable<T> declarations) {
    return ImmutableSetMultimap.copyOf(Multimaps.index(declarations, BindingDeclaration::key));
}

From source file:com.b2international.snowowl.snomed.datastore.request.rf2.importer.Rf2TransactionContext.java

void add(Collection<SnomedComponent> componentChanges,
        Multimap<Class<? extends CDOObject>, String> dependenciesByType) {
    final Multimap<Class<? extends CDOObject>, SnomedComponent> componentChangesByType = Multimaps
            .index(componentChanges, this::getCdoType);
    final List<Class<? extends CDOObject>> typeToImportInOrder = ImmutableList.of(Concept.class,
            Description.class, Relationship.class, SnomedRefSetMember.class);
    for (Class<? extends CDOObject> type : typeToImportInOrder) {
        final Collection<SnomedComponent> rf2Components = componentChangesByType.get(type);
        final Set<String> componentsToLookup = rf2Components.stream().map(IComponent::getId)
                .collect(Collectors.toSet());
        // add all dependencies with the same type
        componentsToLookup.addAll(dependenciesByType.get(type));

        final Map<String, ? extends CDOObject> existingComponents = lookup(componentsToLookup, type);
        final Map<String, ? extends SnomedRefSet> existingRefSets;
        if (SnomedRefSetMember.class == type) {
            existingRefSets = lookup(rf2Components.stream()
                    .map(member -> ((SnomedReferenceSetMember) member).getReferenceSetId())
                    .collect(Collectors.toSet()), SnomedRefSet.class);
        } else {//from   w  ww .j av  a 2s.  co  m
            existingRefSets = Collections.emptyMap();
        }

        // seed missing component before applying row changes
        // and check for existing components with the same or greater effective time and skip them
        final Collection<SnomedComponent> componentsToImport = newArrayList();
        for (SnomedComponent rf2Component : rf2Components) {
            CDOObject existingObject = existingComponents.get(rf2Component.getId());
            if (existingObject == null) {
                // new component, add to new components and apply row
                if (rf2Component instanceof SnomedCoreComponent) {
                    existingObject = createCoreComponent(rf2Component.getId(), type);
                } else if (rf2Component instanceof SnomedReferenceSetMember) {
                    final SnomedReferenceSetMember member = (SnomedReferenceSetMember) rf2Component;
                    existingObject = createMember(rf2Component.getId(), member.type());
                    // seed the refset if missing
                    if (!existingRefSets.containsKey(member.getReferenceSetId())
                            && !newRefSets.containsKey(member.getReferenceSetId())) {
                        final String referencedComponentType = SnomedTerminologyComponentConstants
                                .getTerminologyComponentId(member.getReferencedComponent().getId());
                        String mapTargetComponentType = CoreTerminologyBroker.UNSPECIFIED;
                        try {
                            mapTargetComponentType = SnomedTerminologyComponentConstants
                                    .getTerminologyComponentId((String) member.getProperties()
                                            .get(SnomedRf2Headers.FIELD_MAP_TARGET));
                        } catch (IllegalArgumentException e) {
                            // ignored
                        }
                        SnomedRequests.prepareNewRefSet().setIdentifierId(member.getReferenceSetId())
                                .setType(member.type()).setReferencedComponentType(referencedComponentType)
                                .setMapTargetComponentType(mapTargetComponentType).build().execute(this);

                        newRefSets.put(member.getReferenceSetId(),
                                lookup(member.getReferenceSetId(), SnomedRefSet.class));
                    }
                } else {
                    throw new UnsupportedOperationException("Unsupported component: " + rf2Component);
                }
                newComponents.put(rf2Component.getId(), existingObject);
                componentsToImport.add(rf2Component);
            } else if (existingObject instanceof Component && rf2Component instanceof SnomedCoreComponent) {
                final SnomedCoreComponent rf2Row = (SnomedCoreComponent) rf2Component;
                final Component existingRow = (Component) existingObject;
                if (rf2Row.getEffectiveTime().after(existingRow.getEffectiveTime())) {
                    componentsToImport.add(rf2Component);
                }
            } else if (existingObject instanceof SnomedRefSetMember
                    && rf2Component instanceof SnomedReferenceSetMember) {
                final SnomedReferenceSetMember rf2Row = (SnomedReferenceSetMember) rf2Component;
                final SnomedRefSetMember existingRow = (SnomedRefSetMember) existingObject;
                if (rf2Row.getEffectiveTime().after(existingRow.getEffectiveTime())) {
                    componentsToImport.add(rf2Component);
                }
            }
        }

        // apply row changes
        for (SnomedComponent rf2Component : componentsToImport) {
            CDOObject existingObject = existingComponents.get(rf2Component.getId());
            if (existingObject == null) {
                existingObject = newComponents.get(rf2Component.getId());
            }
            final SnomedComponentBuilder builder;
            if (rf2Component instanceof SnomedCoreComponent) {
                builder = prepareCoreComponent(rf2Component);
            } else if (rf2Component instanceof SnomedReferenceSetMember) {
                builder = prepareMember((SnomedReferenceSetMember) rf2Component);
            } else {
                throw new UnsupportedOperationException("Unsupported component: " + rf2Component);
            }
            builder.init(existingObject, this);
            if (builder instanceof SnomedMemberBuilder) {
                ((SnomedMemberBuilder) builder).addTo(this);
            }
        }
    }
}

From source file:edu.buaa.satla.analysis.core.MainCPAStatistics.java

private void dumpLocationMappedReachedSet(final ReachedSet pReachedSet, CFA cfa, Appendable sb)
        throws IOException {
    final ListMultimap<CFANode, AbstractState> locationIndex = Multimaps.index(pReachedSet, EXTRACT_LOCATION);

    Function<CFANode, String> nodeLabelFormatter = new Function<CFANode, String>() {
        @Override//from   www.  j  av a2 s .co m
        public String apply(CFANode node) {
            StringBuilder buf = new StringBuilder();
            buf.append(node.getNodeNumber()).append("\n");
            for (AbstractState state : locationIndex.get(node)) {
                if (state instanceof Graphable) {
                    buf.append(((Graphable) state).toDOTLabel());
                }
            }
            return buf.toString();
        }
    };
    DOTBuilder.generateDOT(sb, cfa, nodeLabelFormatter);
}

From source file:org.pau.assetmanager.viewmodel.chart.ChartDataModel.java

/**
 * Returns the total balance along one year in a monthly basis.
 * //from w w  w  . ja  v a 2  s. co m
 * @param year
 *            the balance
 * @param yearToAnnotationMultimap
 *            year --> annotations multimap
 * @param selectedBook
 *            book selected for the balance
 * @param bookSelectionType
 *            type of book
 * @return
 */
public static DefaultCategoryDataset getBalance(Integer year,
        Multimap<Integer, Annotation> yearToAnnotationMultimap, BookSelection bookSelection,
        Boolean includePurchasedStocks, Optional<String> optionalStockLabel) {
    Book selectedBook = bookSelection.getSelectedBook();
    Double previousYearsTotals = 0.0;
    for (Integer currentYear : yearToAnnotationMultimap.keySet()) {
        if (currentYear < year) {
            for (Annotation currentAnnotation : yearToAnnotationMultimap.get(currentYear)) {
                previousYearsTotals += currentAnnotation.getSignedAmount();
            }
        }
    }
    Set<StocksBook> stockBooks = new HashSet<StocksBook>();
    Map<String, Double> totalData = new HashMap<String, Double>();
    for (int month = 0; month < 12; month++) {
        Calendar currentcalendar = GregorianCalendar.getInstance();
        currentcalendar.set(Calendar.MONTH, month);
        currentcalendar.set(Calendar.YEAR, year);
        currentcalendar.set(Calendar.DAY_OF_MONTH, 1);
        String mainLabel = getTimeLabel(currentcalendar.getTime());
        totalData.put(mainLabel, 0.0);
        Collection<Annotation> annotations = yearToAnnotationMultimap.get(year);
        if (annotations != null) {
            for (Annotation annotation : annotations) {
                String currentAnnotationLabel = getTimeLabel(annotation.getDate());
                if (currentAnnotationLabel.equals(mainLabel)) {
                    if (annotation.getBook() instanceof StocksBook) {
                        stockBooks.add((StocksBook) annotation.getBook());
                    }
                    totalData.put(mainLabel, totalData.get(mainLabel) + annotation.getSignedAmount());
                }
            }
        }
    }

    DefaultCategoryDataset model = new DefaultCategoryDataset();
    List<String> listOfLabels = getListOfMonthTimeLabelsForYear(year);

    Map<String, Double> labelToToalCumulativeMap = new HashMap<String, Double>();

    Double total = 0.0;
    for (String currentLabel : listOfLabels) {
        Double currentValue = totalData.get(currentLabel);
        if (currentValue != null) {
            total += currentValue;
        }
        labelToToalCumulativeMap.put(currentLabel, total + previousYearsTotals);
    }

    for (String currentLabel : listOfLabels) {
        model.addValue(labelToToalCumulativeMap.get(currentLabel), TOTAL_CUMULATIVE, currentLabel);
    }

    // add stock information in case it is necessary
    if ((selectedBook instanceof StocksBook) && includePurchasedStocks) {
        Table<Integer, Integer, Set<StockState>> historicalStockBalanceStateTable = HistoricalStockBalanceState
                .getConiniousHistoricalStockBalanceStateTable(bookSelection, year, optionalStockLabel);
        Collection<Annotation> annotationsForYear = yearToAnnotationMultimap.get(year);
        if (annotationsForYear == null) {
            annotationsForYear = Lists.newLinkedList();
        }
        Collection<Annotation> movementAnnotationsForYear = Collections2.filter(annotationsForYear,
                new Predicate<Annotation>() {
                    @Override
                    public boolean apply(Annotation input) {
                        return input instanceof MovementExpensesAnnotation
                                || input instanceof MovementIncomeAnnotation;
                    }
                });
        movementAnnotationsForYear = Collections2.filter(movementAnnotationsForYear,
                new Predicate<Annotation>() {
                    @Override
                    public boolean apply(Annotation input) {
                        return input instanceof MovementExpensesAnnotation
                                || input instanceof MovementIncomeAnnotation;
                    }
                });
        final Calendar currentcalendar = GregorianCalendar.getInstance();
        Multimap<Integer, Annotation> monthToAnnotationMultimap = Multimaps.index(movementAnnotationsForYear,
                new Function<Annotation, Integer>() {
                    @Override
                    public Integer apply(Annotation input) {
                        currentcalendar.setTime(input.getDate());
                        return currentcalendar.get(Calendar.MONTH);
                    }
                });

        Double movementBalance = getAllPreviousMovementCumulative(yearToAnnotationMultimap, year);
        if (historicalStockBalanceStateTable != null) {
            Map<Integer, Set<StockState>> historyForYear = historicalStockBalanceStateTable.rowMap().get(year);
            for (Integer currentMonth = 0; currentMonth <= 11; currentMonth++) {
                Double balance = 0.0;
                if (historyForYear != null && historyForYear.get(currentMonth) != null) {
                    for (StockState currentStockState : historyForYear.get(currentMonth)) {
                        balance += currentStockState.getVirtualBalanceForForcedYearAndMonth(year, currentMonth);
                    }
                } else {
                    balance = getYearBeforeFinalVirtualStockBalance(year, historicalStockBalanceStateTable);
                }
                if (monthToAnnotationMultimap.get(currentMonth) != null) {
                    for (Annotation movementAnnotation : monthToAnnotationMultimap.get(currentMonth)) {
                        movementBalance += movementAnnotation.getSignedAmount();
                    }
                }
                model.addValue(balance, TOTAL_CUMULATIVE_STOCKS_PURCHASED, listOfLabels.get(currentMonth));
                Double cumulativeBalance = labelToToalCumulativeMap.get(listOfLabels.get(currentMonth));

                model.addValue(balance + cumulativeBalance - movementBalance, TOTAL_CUMULATIVE_STOCKS_COMBINED,
                        listOfLabels.get(currentMonth));
            }

        }
    }

    return model;
}

From source file:com.b2international.snowowl.snomed.datastore.request.DescriptionRequestHelper.java

private static Multimap<String, SnomedDescription> indexByConceptId(Iterable<SnomedDescription> descriptions) {
    return Multimaps.index(descriptions, description -> description.getConceptId());
}

From source file:dagger.internal.codegen.ComponentModelBuilder.java

protected void addInterfaceMethods() {
    /* Each component method may have been declared by several supertypes. We want to implement only
     * one method for each distinct signature.*/
    ImmutableListMultimap<MethodSignature, ComponentMethodDescriptor> componentMethodsBySignature = Multimaps
            .index(graph.componentDescriptor().entryPointMethods(), this::getMethodSignature);
    for (List<ComponentMethodDescriptor> methodsWithSameSignature : Multimaps.asMap(componentMethodsBySignature)
            .values()) {//from w w w.  j  a  va  2 s .c om
        ComponentMethodDescriptor anyOneMethod = methodsWithSameSignature.stream().findAny().get();
        generatedComponentModel.addMethod(COMPONENT_METHOD,
                bindingExpressions.getComponentMethod(anyOneMethod));
    }
}