Example usage for com.google.common.collect Maps toMap

List of usage examples for com.google.common.collect Maps toMap

Introduction

In this page you can find the example usage for com.google.common.collect Maps toMap.

Prototype

public static <K, V> ImmutableMap<K, V> toMap(Iterator<K> keys, Function<? super K, V> valueFunction) 

Source Link

Document

Returns an immutable map whose keys are the distinct elements of keys and whose value for each key was computed by valueFunction .

Usage

From source file:com.facebook.presto.util.IterableTransformer.java

public <V> MapTransformer<E, V> toMap(Function<? super E, V> valueFunction) {
    return new MapTransformer<>(Maps.toMap(iterable, valueFunction));
}

From source file:org.jamocha.dn.compiler.ecblocks.partition.Partition.java

protected P add(final S newSubSet, final BiFunction<Set<S>, Map<T, S>, P> ctor) {
    assert !newSubSet.elements.values().contains(null);
    assert this.subSets.stream().allMatch(ss -> ss.getElements().keySet().equals(newSubSet.elements.keySet()));
    assert this.subSets.stream()
            .allMatch(ss -> Collections.disjoint(ss.getElements().values(), newSubSet.elements.values()));
    final Set<S> subsets = SetExtender.with(this.subSets, newSubSet);
    final MapCombiner<T, S> lookup = MapCombiner.with(this.lookup,
            Maps.toMap(newSubSet.elements.values(), x -> newSubSet));
    return ctor.apply(subsets, lookup);
}

From source file:com.dangdang.ddframe.rdb.sharding.merger.groupby.GroupByMemoryResultSetMerger.java

private void initForFirstGroupByValue(final ResultSet resultSet, final GroupByValue groupByValue,
        final Map<GroupByValue, MemoryResultSetRow> dataMap,
        final Map<GroupByValue, Map<AggregationSelectItem, AggregationUnit>> aggregationMap)
        throws SQLException {
    if (!dataMap.containsKey(groupByValue)) {
        dataMap.put(groupByValue, new MemoryResultSetRow(resultSet));
    }/*w  w w  .  j av a2 s.  c  om*/
    if (!aggregationMap.containsKey(groupByValue)) {
        Map<AggregationSelectItem, AggregationUnit> map = Maps.toMap(
                selectStatement.getAggregationSelectItems(),
                new Function<AggregationSelectItem, AggregationUnit>() {

                    @Override
                    public AggregationUnit apply(final AggregationSelectItem input) {
                        return AggregationUnitFactory.create(input.getType());
                    }
                });
        aggregationMap.put(groupByValue, map);
    }
}

From source file:com.facebook.buck.core.rules.actions.ActionWrapperDataFactory.java

/**
 * Creates the {@link ActionWrapperData} and its related {@link Action} from a set of {@link
 * DeclaredArtifact}s. The created {@link ActionWrapperData} is registered to the {@link
 * ActionAnalysisDataRegistry}./*from  ww w  . j  a  va  2 s. c  o m*/
 *
 * <p>This will materialize the declared {@link DeclaredArtifact}s into {@link BuildArtifact}s
 * that can be passed via {@link com.google.devtools.build.lib.packages.Provider}s to be consumed.
 *
 * @param actionClazz
 * @param target the built target
 * @param inputs the inputs to the {@link Action}
 * @param outputs the declared outputs of the {@link Action}
 * @param args the arguments for construction the {@link Action}
 * @param <T> the concrete type of the {@link Action}
 * @return a map of the given {@link DeclaredArtifact} to the corresponding {@link BuildArtifact}
 *     to propagate to other rules
 */
@SuppressWarnings("unchecked")
public <T extends AbstractAction> ImmutableMap<DeclaredArtifact, BuildArtifact> createActionAnalysisData(
        Class<T> actionClazz, BuildTarget target, ImmutableSet<Artifact> inputs,
        ImmutableSet<DeclaredArtifact> outputs, Object... args) throws ActionCreationException {
    ActionAnalysisDataKey key = ImmutableActionAnalysisDataKey.of(target, new ID() {
    });
    ImmutableMap<DeclaredArtifact, BuildArtifact> materializedOutputsMap = ImmutableMap
            .copyOf(Maps.toMap(outputs, declared -> declared.materialize(key)));
    Object[] fullArgs = new Object[args.length + 3];
    fullArgs[0] = target;
    fullArgs[1] = inputs;
    fullArgs[2] = materializedOutputsMap.values();
    System.arraycopy(args, 0, fullArgs, 3, args.length);
    try {
        // TODO(bobyf): we can probably do some stuff here with annotation processing to generate
        // typed creation
        T action = (T) actionClazz.getConstructors()[0].newInstance(fullArgs);
        ActionWrapperData actionAnalysisData = ImmutableActionWrapperData.of(key, action);
        actionRegistry.registerAction(actionAnalysisData);

        return materializedOutputsMap;
    } catch (Exception e) {
        throw new ActionCreationException(e, actionClazz, fullArgs);
    }
}

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

private void validateSubcomponentMethods(ValidationReport.Builder<?> report,
        ComponentDescriptor componentDescriptor,
        ImmutableMap<TypeElement, TypeElement> existingModuleToOwners) {
    for (Map.Entry<ComponentMethodDescriptor, ComponentDescriptor> subcomponentEntry : componentDescriptor
            .subcomponentsByFactoryMethod().entrySet()) {
        ComponentMethodDescriptor subcomponentMethodDescriptor = subcomponentEntry.getKey();
        ComponentDescriptor subcomponentDescriptor = subcomponentEntry.getValue();
        // validate the way that we create subcomponents
        for (VariableElement factoryMethodParameter : subcomponentMethodDescriptor.methodElement()
                .getParameters()) {//from   www .  ja  v  a2  s .  c o  m
            TypeElement moduleType = MoreTypes.asTypeElement(factoryMethodParameter.asType());
            TypeElement originatingComponent = existingModuleToOwners.get(moduleType);
            if (originatingComponent != null) {
                /* Factory method tries to pass a module that is already present in the parent.
                 * This is an error. */
                report.addError(String.format(
                        "%s is present in %s. A subcomponent cannot use an instance of a "
                                + "module that differs from its parent.",
                        moduleType.getSimpleName(), originatingComponent.getQualifiedName()),
                        factoryMethodParameter);
            }
        }
        validateSubcomponentMethods(report, subcomponentDescriptor,
                new ImmutableMap.Builder<TypeElement, TypeElement>().putAll(existingModuleToOwners)
                        .putAll(Maps.toMap(
                                Sets.difference(subcomponentDescriptor.transitiveModuleTypes(),
                                        existingModuleToOwners.keySet()),
                                constant(subcomponentDescriptor.componentDefinitionType())))
                        .build());
    }
}

From source file:info.magnolia.ui.dialog.formdialog.FormPresenterImpl.java

@Override
public void presentView(FormViewReduced formView, FormDefinition formDefinition, Item item, FormItem parent) {
    this.formView = formView;
    this.formDefinition = formDefinition;
    this.itemDatasource = item;

    localeToFormSections.clear();/*from   w ww  .j a va  2  s  .co  m*/
    // FormBuilder still expects the FormView object to build, so we have to cast here but ideally that should be refactored
    formBuilder.buildForm((FormView) this.formView, this.formDefinition, item, parent);

    // We should expand locale-awareness onto all the UI contexts.
    if (uiContext instanceof SubAppContext) {
        this.activeLocale = ((SubAppContext) uiContext).getAuthoringLocale();
        formView.setListener(new FormView.Listener() {
            @Override
            public void localeChanged(Locale newLocale) {
                if (newLocale != null
                        && !ObjectUtils.equals(((SubAppContext) uiContext).getAuthoringLocale(), newLocale)) {
                    setLocale(newLocale);
                }
            }
        });

        localeToFormSections.put(this.activeLocale,
                Maps.toMap(formDefinition.getTabs(), new Function<TabDefinition, FormSection>() {
                    @Nullable
                    @Override
                    public FormSection apply(final TabDefinition tabDefinition) {
                        return Iterables.tryFind(FormPresenterImpl.this.formView.getFormSections(),
                                new FormSectionNameMatches(tabDefinition.getName())).orNull();
                    }
                }));
    }
}

From source file:org.opendaylight.distributed.tx.impl.DtxImpl.java

private Map<DTXLogicalTXProviderType, Map<InstanceIdentifier<?>, CachingReadWriteTx>> initializeTransactionsPerLogicalType(
        final Map<DTXLogicalTXProviderType, TxProvider> txProviderMap,
        Map<DTXLogicalTXProviderType, Set<InstanceIdentifier<?>>> nodesMap) {
    Map<DTXLogicalTXProviderType, Map<InstanceIdentifier<?>, CachingReadWriteTx>> typeCacheMap = new HashMap<>(
            txProviderMap.keySet().size());

    for (DTXLogicalTXProviderType type : nodesMap.keySet()) {
        Set<InstanceIdentifier<?>> nodes = nodesMap.get(type);
        final DTXLogicalTXProviderType t = type;
        Map<InstanceIdentifier<?>, CachingReadWriteTx> tmpMap = Maps.toMap(nodes,
                new Function<InstanceIdentifier<?>, CachingReadWriteTx>() {
                    @Nullable/*from   w  w w.  j av  a2  s .c  om*/
                    @Override
                    public CachingReadWriteTx apply(@Nullable final InstanceIdentifier<?> input) {
                        ReadWriteTransaction tx = getTxProviderByType(t).newTx(input);
                        readWriteTxMap.put(input, tx);
                        return new CachingReadWriteTx(tx);
                    }
                });
        typeCacheMap.put(type, tmpMap);
    }

    return typeCacheMap;
}

From source file:org.pau.assetmanager.viewmodel.MonthlyReportViewModel.java

/**
 * @param annotations//from  w w  w. ja  v a2  s.c o m
 * @return the multimap 'Year of Annotaion' --> 'Annotations Involved'
 */
private static Multimap<Integer, Annotation> getYearToAnnotationMultimapFromAnnotations(
        Collection<Annotation> annotations) {
    ImmutableMap<Annotation, Integer> annotationToYear = Maps.toMap(annotations,
            new Function<Annotation, Integer>() {
                @Override
                public Integer apply(Annotation input) {
                    Calendar calendar = GregorianCalendar.getInstance();
                    calendar.setTime(input.getDate());
                    return calendar.get(Calendar.YEAR);
                }
            });
    ListMultimap<Integer, Annotation> yearToAnnotationMultimap = Multimaps
            .invertFrom(Multimaps.forMap(annotationToYear), ArrayListMultimap.<Integer, Annotation>create());
    return yearToAnnotationMultimap;
}

From source file:com.facebook.buck.rules.Genrule.java

protected Genrule(BuildRuleParams buildRuleParams, List<String> srcs, String cmd, String out,
        Function<String, String> relativeToAbsolutePathFunction) {
    super(buildRuleParams);
    this.srcs = ImmutableList.copyOf(srcs);
    this.cmd = Preconditions.checkNotNull(cmd);
    this.srcsToAbsolutePaths = Maps.toMap(srcs, relativeToAbsolutePathFunction);

    Preconditions.checkNotNull(out);/*from w  ww . j ava2s.c o  m*/
    this.outDirectory = String.format("%s/%s", BuckConstant.GEN_DIR,
            buildRuleParams.getBuildTarget().getBasePathWithSlash());
    String outWithGenDirPrefix = String.format("%s%s", outDirectory, out);
    this.outAsAbsolutePath = relativeToAbsolutePathFunction.apply(outWithGenDirPrefix);

    String temp = String.format("%s/%s/%s__tmp", BuckConstant.GEN_DIR,
            buildRuleParams.getBuildTarget().getBasePath(), getBuildTarget().getShortName());
    this.tmpDirectory = relativeToAbsolutePathFunction.apply(temp);

    String srcdir = String.format("%s/%s/%s__srcs", BuckConstant.GEN_DIR,
            buildRuleParams.getBuildTarget().getBasePath(), getBuildTarget().getShortName());
    this.srcDirectory = relativeToAbsolutePathFunction.apply(srcdir);

    this.relativeToAbsolutePathFunction = relativeToAbsolutePathFunction;
}

From source file:fi.hsl.parkandride.core.service.reporting.MaxUtilizationReportService.java

private Map<Long, Map<LocalDate, FacilityStatus>> getFacilityStatusHistory(Set<Long> facilityIds,
        LocalDate startDate, LocalDate endDate) {
    return Maps.toMap(facilityIds, id -> facilityHistoryService.getStatusHistoryByDay(id, startDate, endDate));
}