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:business.category.CategoryDaoGuava.java

public void bulkload() {
    // Bulk-fill the cache at startup time and periodically
    cache.putAll(Maps.uniqueIndex(origin.findAll(), Category::getCategoryId));
}

From source file:com.facebook.presto.memory.ClusterMemoryLeakDetector.java

/**
 * @param queryInfoSupplier All queries that the coordinator knows about.
 * @param queryMemoryReservations The memory reservations of queries in the GENERAL cluster memory pool.
 *//*from  w w  w .  j a  va  2  s . com*/
void checkForMemoryLeaks(Supplier<List<BasicQueryInfo>> queryInfoSupplier,
        Map<QueryId, Long> queryMemoryReservations) {
    requireNonNull(queryInfoSupplier);
    requireNonNull(queryMemoryReservations);

    Map<QueryId, BasicQueryInfo> queryIdToInfo = Maps.uniqueIndex(queryInfoSupplier.get(),
            BasicQueryInfo::getQueryId);

    Map<QueryId, Long> leakedQueryReservations = queryMemoryReservations.entrySet().stream()
            .filter(entry -> entry.getValue() > 0).filter(entry -> isLeaked(queryIdToInfo, entry.getKey()))
            .collect(toImmutableMap(Entry::getKey, Entry::getValue));

    if (!leakedQueryReservations.isEmpty()) {
        log.debug(
                "Memory leak detected. The following queries are already finished, "
                        + "but they have memory reservations on some worker node(s): %s",
                leakedQueryReservations);
    }

    synchronized (this) {
        leakedQueries = ImmutableSet.copyOf(leakedQueryReservations.keySet());
    }
}

From source file:com.facebook.presto.metadata.TablePropertyManager.java

public void addTableProperties(String catalog, List<PropertyMetadata<?>> tableProperties) {
    requireNonNull(catalog, "catalog is null");
    checkArgument(!catalog.isEmpty() && catalog.trim().equals(catalog), "Invalid catalog name '%s'", catalog);
    requireNonNull(tableProperties, "tableProperties is null");

    Map<String, PropertyMetadata<?>> propertiesByName = Maps.uniqueIndex(tableProperties,
            PropertyMetadata::getName);//from w  w w.  j a  v  a 2 s. c om

    checkState(catalogTableProperties.putIfAbsent(catalog, propertiesByName) == null,
            "TableProperties for catalog '%s' are already registered", catalog);
}

From source file:org.ambraproject.wombat.config.theme.ThemeGraph.java

/**
 * Factory method for the graph./*from w  w w. j a  v a2 s. c o m*/
 */
public static ThemeGraph create(Theme rootTheme, Collection<? extends Theme> internalThemes,
        Collection<? extends ThemeBuilder<?>> externalThemes) throws ThemeConfigurationException {
    Preconditions.checkArgument(internalThemes.contains(rootTheme));

    Map<String, ThemeBuilder<?>> themeBuilderMap = externalThemes.stream()
            .collect(Collectors.toMap(ThemeBuilder::getKey, Function.identity()));

    Map<String, Theme> created = new TreeMap<>(); // will eventually contain all themes
    created.putAll(Maps.uniqueIndex(internalThemes, Theme::getKey)); // initialize with internal themes

    // Make repeated passes looking for nodes whose parents have all been created
    int sizeLastPass = 0;
    while (!themeBuilderMap.isEmpty()) {
        for (Iterator<ThemeBuilder<?>> iterator = themeBuilderMap.values().iterator(); iterator.hasNext();) {
            ThemeBuilder<?> node = iterator.next();

            // Search for this node's parents in the map of already-created, immutable themes
            List<String> parentKeys = node.getParentKeys();
            List<Theme> parentThemes = Lists.newArrayListWithCapacity(parentKeys.size());
            for (String parentKey : parentKeys) {
                Theme parentTheme = created.get(parentKey);
                if (parentTheme != null) {
                    parentThemes.add(parentTheme);
                } else if (!themeBuilderMap.containsKey(parentKey)) {
                    throw new ThemeConfigurationException("Unrecognized theme key: " + parentKey);
                } else {
                    // At least one parent has not been created yet
                    parentThemes = null;
                    break;
                }
            }

            if (parentThemes != null) {
                // All parents were found
                Theme immutableNode = node.build(rootTheme, parentThemes);
                created.put(immutableNode.getKey(), immutableNode);
                iterator.remove(); // Remove this node from the to-be-created pool
            } // Else, leave this node in the pool and look for more matches
        }

        // Check that the to-be-created pool shrank by at least 1, to prevent infinite looping
        if (created.size() <= sizeLastPass) {
            throw new ThemeConfigurationException(
                    "A parentage cycle exists within: " + themeBuilderMap.keySet());
        }
        sizeLastPass = created.size();
    }

    return new ThemeGraph(created);
}

From source file:org.jclouds.s3.blobstore.functions.BucketToResourceList.java

public PageSet<? extends StorageMetadata> apply(ListBucketResponse from) {
    Set<StorageMetadata> contents = Sets.<StorageMetadata>newHashSet(Iterables.transform(from, object2blobMd));

    Map<String, StorageMetadata> nameToMd = Maps.uniqueIndex(contents, indexer);
    for (String prefix : from.getCommonPrefixes()) {
        prefix = prefix.endsWith("/") ? prefix.substring(0, prefix.lastIndexOf('/')) : prefix;
        if (!nameToMd.containsKey(prefix) || nameToMd.get(prefix).getType() != StorageType.RELATIVE_PATH)
            contents.add(prefix2ResourceMd.apply(prefix));
    }/*from w ww .  j av a  2 s.c  om*/
    return new PageSetImpl<StorageMetadata>(contents, from.getNextMarker());
}

From source file:com.edmunds.etm.management.api.ManagementVip.java

public static <K, V extends Comparable<? super V>> ImmutableMap<K, V> createSortedMap(Collection<V> poolMembers,
        Function<V, K> indexFunction) {

    final List<V> members = Lists.newArrayList(poolMembers);
    Collections.sort(members);//ww w  .j  a  v a2  s  . c  om

    return Maps.uniqueIndex(members, indexFunction);
}

From source file:org.jboss.seam.social.example.webclient.SocialClient.java

@PostConstruct
public void init() {

    serviceHandlers = Lists.newArrayList(serviceHandlerInstances);
    serviceHandlersMap = Maps.uniqueIndex(serviceHandlerInstances, new Function<OAuthServiceHandler, String>() {

        @Override/*from w w w .  ja v  a 2  s. c  om*/
        public String apply(OAuthServiceHandler arg0) {

            return arg0.getType();
        }
    });

}

From source file:org.apache.aurora.scheduler.storage.db.TaskConfigManager.java

private Optional<Long> getConfigRow(ITaskConfig config) {
    // NOTE: The 'config' object passed in MUST have all version-relevant fields populated in order
    // to correctly compare with objects loaded from DB. This may not hold true if a 'config' is
    // passed from storage recovery routine during version downgrade and fields are not properly
    // backfilled. See AURORA-1603 for more details.

    // We could optimize this slightly by first comparing the un-hydrated row and breaking early.
    Map<ITaskConfig, DbTaskConfig> rowsByConfig = Maps
            .uniqueIndex(configMapper.selectConfigsByJob(config.getJob()), DbTaskConfig::toImmutable);

    return Optional.ofNullable(rowsByConfig.get(config)).map(DbTaskConfig::getRowId);
}

From source file:de.metas.ui.web.picking.packageable.PackageableRowsData.java

private PackageableRowsData(@NonNull final Supplier<List<PackageableRow>> rowsSupplier) {
    topLevelRows = ExtendedMemorizingSupplier
            .of(() -> Maps.uniqueIndex(rowsSupplier.get(), PackageableRow::getId));

    ////from  w  ww . j  a v  a  2 s  . c  o m
    // Remember initial rows
    // We will use this map to figure out what we can invalidate,
    // because we want to cover the case of rows which just vanished (e.g. everything was delivered)
    // and the case of rows which appeared back (e.g. the picking candidate was reactivated so we still have QtyToDeliver).
    initialDocumentIdsByRecordRef = getAllRows().stream().collect(ImmutableListMultimap
            .toImmutableListMultimap(PackageableRow::getTableRecordReference, PackageableRow::getId));
}

From source file:com.google.security.zynamics.binnavi.Database.cache.InstructionCache.java

public void addInstructions(final Iterable<INaviInstruction> instructions) {
    instructionByAddressCache/*from  w w w. j  a  v  a 2  s  .  com*/
            .putAll(Maps.uniqueIndex(instructions, new Function<INaviInstruction, Pair<IAddress, Integer>>() {
                @Override
                public Pair<IAddress, Integer> apply(final INaviInstruction instruction) {
                    return new Pair<IAddress, Integer>(instruction.getAddress(),
                            instruction.getModule().getConfiguration().getId());
                }
            }));
}