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:com.facebook.buck.distributed.DistBuildState.java

private DistBuildState(BuildJobState remoteState, final ImmutableBiMap<Integer, Cell> cells) {
    this.remoteState = remoteState;
    this.cells = cells;
    this.fileHashes = Maps.uniqueIndex(remoteState.getFileHashes(), input -> {
        int cellIndex = input.getCellIndex();
        Cell cell = Preconditions.checkNotNull(cells.get(cellIndex),
                "Unknown cell index %s. Distributed build state dump corrupt?", cellIndex);
        return cell.getFilesystem();
    });//w  ww. java 2s.  com

    this.directFileHashCacheLoder = CacheBuilder.newBuilder()
            .build(new CacheLoader<ProjectFilesystem, FileHashCache>() {
                @Override
                public FileHashCache load(@Nonnull ProjectFilesystem filesystem) {
                    FileHashCache cellCache = DefaultFileHashCache.createDefaultFileHashCache(filesystem);
                    FileHashCache buckOutCache = DefaultFileHashCache.createBuckOutFileHashCache(
                            filesystem.replaceBlacklistedPaths(ImmutableSet.of()),
                            filesystem.getBuckPaths().getBuckOut());
                    return new StackedFileHashCache(ImmutableList.of(cellCache, buckOutCache));
                }
            });
}

From source file:be.nbb.sdmx.bancaditalia.SdmxConnectionSupplierImpl.java

private static Map<String, GenericSDMXClient> createClients() {
    try {//from  w ww .j  a v  a 2s .co  m
        List<GenericSDMXClient> result = Arrays.<GenericSDMXClient>asList(new ABS(), new ILO(), new IMF(),
                new INEGI(), new OECD(), new WB(), new NBB(), new UIS());
        return Maps.uniqueIndex(result, new Function<GenericSDMXClient, String>() {
            @Override
            public String apply(GenericSDMXClient input) {
                try {
                    return input.getEndpoint().getHost();
                } catch (SdmxException ex) {
                    throw new RuntimeException(ex);
                }
            }
        });
    } catch (MalformedURLException ex) {
        throw new RuntimeException(ex);
    }
}

From source file:de.metas.ui.web.window.descriptor.filters.ImmutableDocumentFilterDescriptorsProvider.java

public ImmutableDocumentFilterDescriptorsProvider(final List<DocumentFilterDescriptor> descriptors) {
    super();//from w ww  . j av a 2  s  . c o m
    descriptorsByFilterId = Maps.uniqueIndex(descriptors, descriptor -> descriptor.getFilterId());
}

From source file:de.faustedition.genesis.lines.VerseStatisticsResource.java

@Get("json")
public Representation chartData() {
    final List<Map<String, Object>> chartData = Lists.newLinkedList();
    final ImmutableMap<String, MaterialUnit> documentIndex = Maps.uniqueIndex(verseStatistics.keySet(),
            new Function<MaterialUnit, String>() {
                @Override/*from  w  w  w.  j a  v  a  2  s.c  om*/
                public String apply(@Nullable MaterialUnit input) {
                    return input.toString() + " [" + input.node.getId() + "]";
                }
            });
    for (String documentDesc : Ordering.natural().immutableSortedCopy(documentIndex.keySet())) {
        final List<Map<String, Object>> intervals = Lists.newLinkedList();
        for (VerseInterval interval : Ordering.from(VerseManager.INTERVAL_COMPARATOR)
                .immutableSortedCopy(verseStatistics.get(documentIndex.get(documentDesc)))) {
            intervals.add(new ModelMap().addAttribute("start", Math.max(from, interval.getStart()))
                    .addAttribute("end", Math.min(to, interval.getEnd())));
        }
        chartData.add(new ModelMap().addAttribute("sigil", documentDesc.substring(0, documentDesc.indexOf('[')))
                /*.addAttribute("transcript", documentIndex.get(documentDesc).node.getId())*/
                .addAttribute("source", ((Document) documentIndex.get(documentDesc)).getSource().toString())
                .addAttribute("intervals", intervals));
    }
    return jsonRepresentationFactory.map(chartData, false);
}

From source file:org.jclouds.openstack.keystone.v2_0.suppliers.LocationIdToURIFromAccessForTypeAndVersionSupplier.java

@Override
public Map<String, Supplier<URI>> get() {
    Access accessResponse = access.get();
    Service service = null;/*from   w ww. ja va 2 s  .  co m*/
    try {
        service = Iterables.find(accessResponse.getServiceCatalog(), new Predicate<Service>() {

            @Override
            public boolean apply(Service input) {
                return input.getType().equals(apiType);
            }

        });
    } catch (NoSuchElementException e) {
        throw new NoSuchElementException(String.format("apiType %s not found in catalog %s", apiType,
                accessResponse.getServiceCatalog()));
    }
    Map<String, Endpoint> locationIdToEndpoint = Maps
            .uniqueIndex(Iterables.filter(service.getEndpoints(), new Predicate<Endpoint>() {

                @Override
                public boolean apply(Endpoint input) {
                    if (input.getVersionId() == null) {
                        return true;
                    }
                    return input.getVersionId().equals(apiVersion);
                }

            }), endpointToLocationId);
    return Maps.transformValues(locationIdToEndpoint, endpointToSupplierURI);
}

From source file:org.jclouds.smartos.compute.strategy.SmartOSComputeServiceAdapter.java

@Inject
public SmartOSComputeServiceAdapter(SmartOSHostController host) {
    this.host = checkNotNull(host, "host");

    Collection<VmSpecification> specifications = Lists.newArrayList();

    specifications.add(VmSpecification.builder().alias("Standard Joyent VM, 1Gb RAM / 2Gb SWAP").ram(1024)
            .maxSwap(2048).nic(VmNIC.builder().simpleDHCPNic().build()).build());

    specifications.add(VmSpecification.builder().alias("Standard Joyent VM, 2Gb RAM / 4Gb SWAP").ram(2048)
            .maxSwap(4096).nic(VmNIC.builder().simpleDHCPNic().build()).build());

    specifications.add(VmSpecification.builder().alias("Standard Joyent VM, 4Gb RAM / 8Gb SWAP").ram(4096)
            .maxSwap(8192).nic(VmNIC.builder().simpleDHCPNic().build()).build());

    specifications.add(VmSpecification.builder().alias("Standard Joyent VM, 8Gb RAM / 16Gb SWAP").ram(8192)
            .maxSwap(16384).nic(VmNIC.builder().simpleDHCPNic().build()).build());

    specificationMap = Maps.uniqueIndex(specifications, new Function<VmSpecification, String>() {
        @Override/*w w  w . jav a 2s.  com*/
        public String apply(VmSpecification input) {
            return input.getAlias();
        }
    });

}

From source file:io.crate.analyze.InsertFromSubQueryAnalyzedStatement.java

public InsertFromSubQueryAnalyzedStatement(QueriedRelation subQueryRelation, DocTableInfo tableInfo,
        List<Reference> targetColumns, @Nullable Map<Reference, Symbol> onDuplicateKeyAssignments) {
    this.targetTable = tableInfo;
    this.subQueryRelation = subQueryRelation;
    this.onDuplicateKeyAssignments = onDuplicateKeyAssignments;
    this.targetColumns = targetColumns;
    Map<ColumnIdent, Integer> columnPositions = toPositionMap(targetColumns);

    clusteredByIdx = MoreObjects.firstNonNull(columnPositions.get(tableInfo.clusteredBy()), -1);
    ImmutableMap<ColumnIdent, GeneratedReference> generatedColumns = Maps
            .uniqueIndex(tableInfo.generatedColumns(), Reference.TO_COLUMN_IDENT);

    if (tableInfo.hasAutoGeneratedPrimaryKey()) {
        this.primaryKeySymbols = Collections.emptyList();
    } else {/*from   w  w w . ja  va  2 s.  co  m*/
        this.primaryKeySymbols = symbolsFromTargetColumnPositionOrGeneratedExpression(columnPositions,
                targetColumns, tableInfo.primaryKey(), generatedColumns);
    }
    this.partitionedBySymbols = symbolsFromTargetColumnPositionOrGeneratedExpression(columnPositions,
            targetColumns, tableInfo.partitionedBy(), generatedColumns);
}

From source file:com.opengamma.financial.security.cds.CDSIndexComponentBundle.java

/**
 * Creates a cdsIndex components bundle from a set of cdsIndex
 * component and a comparator./*w  w  w . j  av a 2  s . c om*/
 *
 * @param components  the set of components assigned, not null
 */
private CDSIndexComponentBundle(Iterable<CreditDefaultSwapIndexComponent> components,
        Comparator<? super CreditDefaultSwapIndexComponent> comparator) {
    ArgumentChecker.notEmpty(components, "components");
    ArgumentChecker.noNulls(components, "components");
    ArgumentChecker.notNull(comparator, "comparator");

    _components = ImmutableSortedSet.copyOf(comparator, deduplicate(components));
    _redCodeMapping = Maps.uniqueIndex(_components,
            new Function<CreditDefaultSwapIndexComponent, ExternalId>() {
                @Override
                public ExternalId apply(CreditDefaultSwapIndexComponent input) {
                    return input.getObligorRedCode();
                }
            });
}

From source file:org.estatio.dom.geography.Countries.java

@Programmatic
public List<Country> countriesFor(final Iterable<String> countryCodes) {
    List<Country> available = Lists.newArrayList();
    final ImmutableMap<String, Country> countryByCode = Maps.uniqueIndex(allCountries(),
            new Function<Country, String>() {
                @Override/*from  w  w w . j  a  v  a  2s.  c  o m*/
                public String apply(final Country input) {
                    return input.getName();
                }
            });
    for (String countryCodeForUser : countryCodes) {
        available.add(countryByCode.get(countryCodeForUser));
    }
    return available;
}

From source file:com.facebook.presto.connector.system.SystemDataStreamProvider.java

private RecordSet createRecordSet(Split split, List<ColumnHandle> columns) {
    checkNotNull(split, "split is null");
    checkArgument(split instanceof SystemSplit, "Split must be of type %s, not %s", SystemSplit.class.getName(),
            split.getClass().getName());
    SchemaTableName tableName = ((SystemSplit) split).getTableHandle().getSchemaTableName();

    checkNotNull(columns, "columns is null");
    checkArgument(!columns.isEmpty(), "must provide at least one column");

    SystemTable systemTable = tables.get(tableName);
    checkArgument(systemTable != null, "Table %s does not exist", tableName);
    Map<String, ColumnMetadata> columnsByName = Maps.uniqueIndex(systemTable.getTableMetadata().getColumns(),
            columnNameGetter());/*from  w  w  w  .  j  a  v  a 2 s. com*/

    ImmutableList.Builder<Integer> userToSystemFieldIndex = ImmutableList.builder();
    for (ColumnHandle column : columns) {
        checkArgument(column instanceof SystemColumnHandle, "column must be of type %s, not %s",
                SystemColumnHandle.class.getName(), column.getClass().getName());
        String columnName = ((SystemColumnHandle) column).getColumnName();

        ColumnMetadata columnMetadata = columnsByName.get(columnName);
        checkArgument(columnMetadata != null, "Column %s.%s does not exist", tableName, columnName);

        userToSystemFieldIndex.add(columnMetadata.getOrdinalPosition());
    }

    return new MappedRecordSet(systemTable, userToSystemFieldIndex.build());
}