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.calrissian.mango.collect.FluentCloseableIterable.java

/**
 * Returns an immutable map for which the {@link java.util.Map#values} are the elements of this
 * {@code FluentIterable} in the given order, and each key is the product of invoking a supplied
 * function on its corresponding value.//from   w w  w. j  ava 2s .c  o m
 *
 * @param keyFunction the function used to produce the key for each value
 * @throws IllegalArgumentException if {@code keyFunction} produces the same key for more than one
 *     value in this fluent iterable
 * @throws NullPointerException if any element of this fluent iterable is null, or if
 *     {@code keyFunction} produces {@code null} for any value
 */
public final <K> ImmutableMap<K, T> uniqueIndex(Function<? super T, K> keyFunction) {
    return Maps.uniqueIndex(this, keyFunction);
}

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

/**
 * @param pushRequests what was actually requested to push
 * @param previousRemoteRefs the state of the remote refs before the data transfer
 * @param remoteRepo the remote repo//from   ww  w . ja  va 2s .c  o m
 * @return the updated list of what's currently in the remote and what's been updated on the
 *         remote refs once this method finishes
 */
private List<RefDiff> updateRemoteRefs(List<PushReq> pushRequests, Set<Ref> previousRemoteRefs,
        IRemoteRepo remoteRepo) {

    final Map<String, Ref> beforeRemoteRefs = Maps.uniqueIndex(previousRemoteRefs, (r) -> r.getName());

    List<RefDiff> results = new ArrayList<>();

    final Repository local = repository();

    for (PushReq pr : pushRequests) {
        if (pr.delete) {
            // REVISIT: should remote remove the ref only if it still has the same value it had
            // before the op?
            Optional<Ref> deleted = remoteRepo.deleteRef(pr.remoteRef);
            if (deleted.isPresent()) {
                results.add(RefDiff.removed(deleted.get()));
            }
            continue;
        }
        final String updateRefName = pr.remoteRef;
        final @Nullable Ref oldRef = beforeRemoteRefs.get(updateRefName);
        final @Nullable ObjectId oldValue = oldRef == null ? null : oldRef.getObjectId();
        final ObjectId updateValue = pr.localRef.getObjectId();
        if (updateValue.equals(oldValue)) {
            continue;
        }
        // will fail if current value has changed
        Optional<Ref> remoteRef = remoteRepo.command(UpdateRef.class)//
                .setName(updateRefName)//
                .setOldValue(oldRef == null ? null : oldRef.getObjectId())//
                .setNewValue(updateValue)//
                .call();

        Preconditions.checkArgument(remoteRef.isPresent());
        Ref localRemoteRef = local.command(MapRef.class)//
                .setRemote(remoteRepo.getInfo())//
                .add(remoteRef.get())//
                .convertToRemote().call().get(0);
        local.command(UpdateRef.class)//
                .setName(localRemoteRef.getName())//
                .setNewValue(localRemoteRef.getObjectId())//
                .call();

        RefDiff result = new RefDiff(oldRef, remoteRef.get());
        results.add(result);
    }
    return results;
}

From source file:com.facebook.presto.sql.planner.assertions.PlanMatchPattern.java

private static PlanMatchPattern values(List<String> aliases, Optional<List<List<Expression>>> expectedRows) {
    return values(Maps.uniqueIndex(IntStream.range(0, aliases.size()).boxed().iterator(), aliases::get),
            Optional.of(aliases.size()), expectedRows);
}

From source file:org.sonar.ide.eclipse.internal.ui.views.MeasuresView.java

public Map<String, Metric> getMetrics(EclipseSonar index) {
    // TODO Godin: This is not optimal. Would be better to load metrics only once.
    List<Metric> metrics = index.getSonar().findAll(MetricQuery.all());
    return Maps.uniqueIndex(metrics, new Function<Metric, String>() {
        public String apply(Metric metric) {
            return metric.getKey();
        }/*from   w  w w  .j a v  a  2 s  .c o  m*/
    });
}

From source file:org.graylog2.security.ldap.LdapSettingsImpl.java

@Override
public void setAdditionalDefaultGroups(Set<String> groupNames) {
    try {/*from  www .  j av a2s. co  m*/
        if (groupNames == null)
            return;

        final Map<String, Role> nameToRole = Maps.uniqueIndex(roleService.loadAll(),
                Roles.roleToNameFunction());
        final List<String> groupIds = Lists
                .newArrayList(Collections2.transform(groupNames, new Function<String, String>() {
                    @Nullable
                    @Override
                    public String apply(@Nullable String groupName) {
                        if (groupName == null || !nameToRole.containsKey(groupName)) {
                            return null;
                        }
                        return nameToRole.get(groupName).getId();
                    }
                }));
        fields.put(ADDITIONAL_DEFAULT_GROUPS, groupIds);
    } catch (NotFoundException e) {
        LOG.error("Unable to convert group names to ids", e);
        throw new IllegalStateException("Unable to convert group names to ids", e);
    }

}

From source file:com.turn.griffin.GriffinLibCacheUtil.java

public Map<String, File> getLocalFileMap() {
    List<File> fileList = getLocalFileList();
    return Maps.uniqueIndex(fileList, new Function<File, String>() {
        @Nullable//from w  w w  . ja v a 2s.c o m
        @Override
        public String apply(File file) {
            return file.getName();
        }
    });
}

From source file:net.minecraftforge.fml.common.Loader.java

/**
 * The primary loading code/*from  ww w .j ava  2  s  . c o  m*/
 *
 *
 * The found resources are first loaded into the {@link #modClassLoader}
 * (always) then scanned for class resources matching the specification
 * above.
 *
 * If they provide the {@link Mod} annotation, they will be loaded as
 * "FML mods"
 *
 * Finally, if they are successfully loaded as classes, they are then added
 * to the available mod list.
 */
private ModDiscoverer identifyMods() {
    FMLLog.fine("Building injected Mod Containers %s", injectedContainers);
    // Add in the MCP mod container
    mods.add(new InjectedModContainer(mcp, new File("minecraft.jar")));
    for (String cont : injectedContainers) {
        ModContainer mc;
        try {
            mc = (ModContainer) Class.forName(cont, true, modClassLoader).newInstance();
        } catch (Exception e) {
            FMLLog.log(Level.ERROR, e, "A problem occured instantiating the injected mod container %s", cont);
            throw new LoaderException(e);
        }
        mods.add(new InjectedModContainer(mc, mc.getSource()));
    }
    ModDiscoverer discoverer = new ModDiscoverer();
    FMLLog.fine("Attempting to load mods contained in the minecraft jar file and associated classes");
    discoverer.findClasspathMods(modClassLoader);
    FMLLog.fine("Minecraft jar mods loaded successfully");

    FMLLog.getLogger().log(Level.INFO, "Found {} mods from the command line. Injecting into mod discoverer",
            ModListHelper.additionalMods.size());
    FMLLog.info("Searching %s for mods", canonicalModsDir.getAbsolutePath());
    discoverer.findModDirMods(canonicalModsDir, ModListHelper.additionalMods.values().toArray(new File[0]));
    File versionSpecificModsDir = new File(canonicalModsDir, mccversion);
    if (versionSpecificModsDir.isDirectory()) {
        FMLLog.info("Also searching %s for mods", versionSpecificModsDir);
        discoverer.findModDirMods(versionSpecificModsDir);
    }

    mods.addAll(discoverer.identifyMods());
    identifyDuplicates(mods);
    namedMods = Maps.uniqueIndex(mods, new ModIdFunction());
    FMLLog.info("Forge Mod Loader has identified %d mod%s to load", mods.size(), mods.size() != 1 ? "s" : "");
    return discoverer;
}

From source file:org.sonar.server.rule.ws.SearchAction.java

private SearchResult doSearch(DbSession dbSession, RuleQuery query, SearchOptions context) {
    SearchIdResult<RuleKey> result = ruleIndex.search(query, context);
    List<RuleKey> ruleKeys = result.getIds();
    // rule order is managed by ES
    Map<RuleKey, RuleDto> rulesByRuleKey = Maps.uniqueIndex(
            dbClient.ruleDao().selectByKeys(dbSession, query.getOrganizationUuid(), ruleKeys), RuleDto::getKey);
    List<RuleDto> rules = new ArrayList<>();
    for (RuleKey ruleKey : ruleKeys) {
        RuleDto rule = rulesByRuleKey.get(ruleKey);
        if (rule != null) {
            rules.add(rule);/*www .j  a  v  a 2s  . c om*/
        }
    }
    List<Integer> ruleIds = rules.stream().map(RuleDto::getId).collect(MoreCollectors.toList());
    List<Integer> templateRuleIds = rules.stream().map(RuleDto::getTemplateId).filter(Objects::nonNull)
            .collect(MoreCollectors.toList());
    List<RuleDefinitionDto> templateRules = dbClient.ruleDao().selectDefinitionByIds(dbSession,
            templateRuleIds);
    List<RuleParamDto> ruleParamDtos = dbClient.ruleDao().selectRuleParamsByRuleIds(dbSession, ruleIds);
    return new SearchResult().setRules(rules).setRuleParameters(ruleParamDtos).setTemplateRules(templateRules)
            .setFacets(result.getFacets()).setTotal(result.getTotal());
}

From source file:org.locationtech.geogig.api.RevTreeBuilder.java

private Map<Integer, RevTree> getBucketTrees(ImmutableSet<Integer> changedBucketIndexes) {
    Map<Integer, RevTree> bucketTrees = new HashMap<>();
    List<Integer> missing = new ArrayList<>(changedBucketIndexes.size());
    for (Integer bucketIndex : changedBucketIndexes) {
        Bucket bucket = bucketTreesByBucket.get(bucketIndex);
        RevTree cached = bucket == null ? RevTree.EMPTY : pendingWritesCache.get(bucket.id());
        if (cached == null) {
            missing.add(bucketIndex);/*w w  w  .j  a v a2s . c  om*/
        } else {
            bucketTrees.put(bucketIndex, cached);
        }
    }
    if (!missing.isEmpty()) {
        Map<ObjectId, Integer> ids = Maps.uniqueIndex(missing, new Function<Integer, ObjectId>() {
            @Override
            public ObjectId apply(Integer index) {
                return bucketTreesByBucket.get(index).id();
            }
        });
        Iterator<RevObject> all = db.getAll(ids.keySet());
        while (all.hasNext()) {
            RevObject next = all.next();
            bucketTrees.put(ids.get(next.getId()), (RevTree) next);
        }
    }
    return bucketTrees;
}

From source file:org.polarsys.reqcycle.repository.data.impl.DataManagerImpl.java

@Override
public boolean visit(IResourceDelta delta) throws CoreException {
    IResource res = delta.getResource();
    if (res instanceof IFile && ((IFile) res).getFileExtension().equals("reqcycle")) {
        Map<URI, RequirementSource> setSources = Maps.uniqueIndex(sources.getRequirementSources(),
                new Function<RequirementSource, URI>() {

                    @Override/*www .  j  a  v  a 2  s .  c  o m*/
                    public URI apply(RequirementSource arg0) {
                        return URI.createURI(arg0.getDestinationURI());
                    }

                });
        URI platform = URI.createPlatformResourceURI(res.getFullPath().toString(), true);
        final RequirementSource reqSource = setSources.get(platform);
        if (reqSource != null) {
            try {
                Resource r = confManager.getConfigurationResourceSet().getResource(platform, false);
                if (r != null && r.isLoaded()) {
                    r.unload();
                    r.load(Collections.emptyMap());

                    ViewerNotification notification = new ViewerNotification(
                            new NotificationImpl(Notification.SET, r, r) {
                                @Override
                                public Object getNotifier() {
                                    return reqSource;
                                }
                            }, reqSource.getContents());
                    reqSource.eNotify(notification);
                }
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }
    return true;
}