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

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

Introduction

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

Prototype

public static <K, V> ImmutableMap<K, V> uniqueIndex(Iterator<V> values, Function<? super V, K> keyFunction) 

Source Link

Document

Returns a map with the given values , indexed by keys derived from those values.

Usage

From source file:org.locationtech.geogig.remotes.pack.PackImpl.java

private List<ObjectId[]> collectMissingRootTreeIdPairs(List<RevCommit> commits, ObjectDatabase sourceStore) {

    final Map<ObjectId, RevCommit> rootsById = new HashMap<>(Maps.uniqueIndex(commits, (c) -> c.getId()));

    List<ObjectId[]> diffRootTreeIds = new ArrayList<>();

    for (RevCommit commit : commits) {

        final ObjectId rightTreeId = commit.getTreeId();
        List<ObjectId> parentIds = commit.getParentIds();
        if (parentIds.isEmpty()) {
            diffRootTreeIds.add(new ObjectId[] { RevTree.EMPTY_TREE_ID, rightTreeId });
            continue;
        }//from   w  w  w.  j a v a2  s .c o  m
        for (ObjectId parentId : parentIds) {
            final @Nullable RevCommit parent = parentId.isNull() ? null
                    : Optional.fromNullable((RevCommit) rootsById.get(parentId))
                            .or(() -> source.getCommit(parentId));

            ObjectId oldRootTreeId = parent == null ? RevTree.EMPTY_TREE_ID : parent.getTreeId();
            diffRootTreeIds.add(new ObjectId[] { oldRootTreeId, rightTreeId });
        }
    }

    return diffRootTreeIds;
}

From source file:org.sonar.server.measure.custom.ws.SearchAction.java

private Map<Integer, MetricDto> metricsById(DbSession dbSession, List<CustomMeasureDto> customMeasures) {
    List<MetricDto> metrics = dbClient.metricDao().selectByIds(dbSession,
            newHashSet(Lists.transform(customMeasures, CustomMeasureToMetricIdFunction.INSTANCE)));
    return Maps.uniqueIndex(metrics, MetricToIdFunction.INSTANCE);
}

From source file:com.facebook.presto.cassandra.CachingCassandraSchemaProvider.java

private Map<String, String> loadAllSchemas() throws Exception {
    return retry().stopOnIllegalExceptions().run("getAllSchemas",
            () -> Maps.uniqueIndex(session.getAllSchemas(), CachingCassandraSchemaProvider::toLowerCase));
}

From source file:com.isotrol.impe3.pms.core.impl.EditionsServiceImpl.java

private void createEdition(EnvironmentEntity env, Predicate<UUID> portals) throws PMSException {
    final EditionEntity edition = new EditionEntity();
    edition.setLastPublished(loadUser());
    saveNew(edition);//from w  w w.  ja va 2  s.  co m
    // 1 - Content types
    for (ContentTypeEntity e : env.getOfflineContentTypes()) {
        final ContentTypeEdition edt = new ContentTypeEdition();
        edt.setEdition(edition);
        edt.setPublished(e.getCurrent());
        setPublishedFlag(e.getCurrent());
        saveNewEntity(edt);
    }
    // 2 - Categories
    for (CategoryEntity e : env.getOfflineCategories()) {
        final CategoryEdition edt = new CategoryEdition();
        edt.setEdition(edition);
        edt.setPublished(e.getCurrent());
        setPublishedFlag(e.getCurrent());
        saveNewEntity(edt);
    }
    // 3 - Connectors
    for (ConnectorEntity e : env.getOfflineConnectors()) {
        final ConnectorEdition edt = new ConnectorEdition();
        edt.setEdition(edition);
        edt.setPublished(e.getCurrent());
        setPublishedFlag(e.getCurrent());
        saveNewEntity(edt);
    }
    // 4 - Portals
    if (portals == null) {
        for (PortalEntity e : env.getOfflinePortals()) {
            newPortalEdition(edition, e.getCurrent());
        }
    } else {
        Map<UUID, PortalEdition> map = Maps.uniqueIndex(env.getCurrent().getPortals(), PortalEdition.ENTITY_ID);
        for (PortalEntity e : env.getOfflinePortals()) {
            final UUID id = e.getId();
            final PortalDfn dfn;
            if (portals.apply(id)) {
                dfn = e.getCurrent();
            } else if (map.containsKey(id)) {
                dfn = map.get(id).getPublished();
            } else {
                dfn = null;
            }
            if (dfn != null) {
                newPortalEdition(edition, dfn);
            }
        }
    }
    // We set the current edition
    env.setCurrent(edition);
}

From source file:org.apache.aurora.scheduler.storage.mem.MemTaskStore.java

@Timed("mem_storage_save_tasks")
@Override/* w  ww .  j  a v  a 2 s .c om*/
public void saveTasks(Set<IScheduledTask> newTasks) {
    requireNonNull(newTasks);
    Preconditions.checkState(Tasks.ids(newTasks).size() == newTasks.size(),
            "Proposed new tasks would create task ID collision.");

    Iterable<Task> canonicalized = Iterables.transform(newTasks, toTask);
    tasks.putAll(Maps.uniqueIndex(canonicalized, TO_ID));
    for (SecondaryIndex<?> index : secondaryIndices) {
        index.insert(Iterables.transform(canonicalized, TO_SCHEDULED));
    }
}

From source file:com.facebook.presto.mysql.CachingMySQLSchemaProvider.java

private Map<String, String> loadAllSchemas() throws Exception {
    return retry().stopOnIllegalExceptions().run("getAllSchemas", new Callable<Map<String, String>>() {
        @Override/* ww w  .j a v a  2 s. c o  m*/
        public Map<String, String> call() {
            return Maps.uniqueIndex(session.getAllSchemas(), toLowerCase());
        }
    });
}

From source file:org.codice.ddf.ui.searchui.query.controller.search.QueryRunnable.java

protected void addResults(Collection<Result> responseResults) {
    results.putAll(Maps.uniqueIndex(responseResults, new Function<Result, String>() {
        @Override//w  w w  . ja va 2 s.  co m
        public String apply(Result result) {
            return getResultKey(result.getMetacard());
        }
    }));
}

From source file:com.microsoft.azure.management.appservice.implementation.AppServiceBaseImpl.java

@Override
@SuppressWarnings("unchecked")
public Observable<Map<String, HostNameBinding>> getHostNameBindingsAsync() {
    return this.manager().inner().webApps().listHostNameBindingsAsync(resourceGroupName(), name())
            .flatMap(new Func1<Page<HostNameBindingInner>, Observable<HostNameBindingInner>>() {
                @Override/* ww  w  .  j av a2s.  com*/
                public Observable<HostNameBindingInner> call(
                        Page<HostNameBindingInner> hostNameBindingInnerPage) {
                    return Observable.from(hostNameBindingInnerPage.items());
                }
            }).map(new Func1<HostNameBindingInner, HostNameBinding>() {
                @Override
                public HostNameBinding call(HostNameBindingInner hostNameBindingInner) {
                    return new HostNameBindingImpl<>(hostNameBindingInner,
                            (FluentImplT) AppServiceBaseImpl.this);
                }
            }).toList().map(new Func1<List<HostNameBinding>, Map<String, HostNameBinding>>() {
                @Override
                public Map<String, HostNameBinding> call(List<HostNameBinding> hostNameBindings) {
                    return Collections.unmodifiableMap(
                            Maps.uniqueIndex(hostNameBindings, new Function<HostNameBinding, String>() {
                                @Override
                                public String apply(HostNameBinding input) {
                                    return input.name().replace(name() + "/", "");
                                }
                            }));
                }
            });
}

From source file:org.sonar.server.measure.ws.ComponentAction.java

private static ComponentWsResponse buildResponse(ComponentWsRequest request, ComponentDto component,
        Optional<ComponentDto> refComponent, List<MeasureDto> measures, List<MetricDto> metrics,
        List<WsMeasures.Period> periods) {
    ComponentWsResponse.Builder response = ComponentWsResponse.newBuilder();
    Map<Integer, MetricDto> metricsById = Maps.uniqueIndex(metrics, MetricDto::getId);
    Map<MetricDto, MeasureDto> measuresByMetric = new HashMap<>();
    for (MeasureDto measure : measures) {
        MetricDto metric = metricsById.get(measure.getMetricId());
        measuresByMetric.put(metric, measure);
    }//www.  j  av a 2  s  .c  o  m
    if (refComponent.isPresent()) {
        response.setComponent(componentDtoToWsComponent(component, measuresByMetric,
                singletonMap(refComponent.get().uuid(), refComponent.get())));
    } else {
        response.setComponent(componentDtoToWsComponent(component, measuresByMetric, emptyMap()));
    }

    List<String> additionalFields = request.getAdditionalFields();
    if (additionalFields != null) {
        if (additionalFields.contains(ADDITIONAL_METRICS)) {
            for (MetricDto metric : metrics) {
                response.getMetricsBuilder().addMetrics(metricDtoToWsMetric(metric));
            }
        }
        if (additionalFields.contains(ADDITIONAL_PERIODS)) {
            response.getPeriodsBuilder().addAllPeriods(periods);
        }
    }

    return response.build();
}

From source file:org.locationtech.geogig.plumbing.merge.DiffMergeFeaturesOp.java

private Map<ObjectId, RevObject> getObjects() {

    final ObjectId ancestorMetadataId = commonAncestor.getMetadataId();
    final ObjectId mergetIntoMetadataId = mergeInto.getMetadataId();
    final ObjectId toMergeMetadataId = toMerge.getMetadataId();

    final ObjectId ancestorFeatureId = commonAncestor.getObjectId();
    final ObjectId featureAId = mergeInto.getObjectId();
    final ObjectId featureBId = toMerge.getObjectId();

    Set<ObjectId> ids = Sets.newHashSet(ancestorMetadataId, mergetIntoMetadataId, toMergeMetadataId,
            ancestorFeatureId, featureAId, featureBId);

    Iterator<RevObject> objsit = objectDatabase().getAll(ids, BulkOpListener.NOOP_LISTENER);

    ImmutableMap<ObjectId, RevObject> map = Maps.uniqueIndex(objsit, (o) -> o.getId());

    if (ids.size() != map.size()) {
        ids.forEach((id) -> checkState(map.containsKey(id), "Invalid reference: %s", id));
    }/*from  w w w  .  j a va2 s . co  m*/
    return map;
}