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.incode.module.country.dom.impl.CountryRepository.java

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

From source file:org.jclouds.virtualbox.functions.admin.ImageFromYamlStream.java

@Override
public LoadingCache<String, Image> apply(InputStream source) {

    Constructor constructor = new Constructor(Config.class);

    TypeDescription imageDesc = new TypeDescription(YamlImage.class);
    imageDesc.putListPropertyType("images", String.class);
    constructor.addTypeDescription(imageDesc);

    Yaml yaml = new Yaml(new Loader(constructor));
    Config config = (Config) yaml.load(source);
    checkState(config != null, "missing config: class");
    checkState(config.images != null, "missing images: collection");

    Map<String, Image> backingMap = Maps.uniqueIndex(Iterables.transform(config.images, YamlImage.toImage),
            new Function<Image, String>() {
                public String apply(Image image) {
                    return image.getId();
                }//from   w  w  w  .  j ava 2s.c om
            });
    LoadingCache<String, Image> cache = CacheBuilder.newBuilder()
            .build(CacheLoader.from(Functions.forMap(backingMap)));
    for (String node : backingMap.keySet())
        cache.getUnchecked(node);
    return cache;
}

From source file:org.pau.assetmanager.viewmodel.stocks.HistoricalStockBalanceState.java

public static Table<Integer, Integer, Set<StockState>> getConiniousHistoricalStockBalanceStateTable(
        BookSelection bookSelection, Integer lastYear, Optional<String> optionalStockLabel) {
    Table<Integer, Integer, Set<StockState>> uncontiniousHistoricalStockBalanceStateTable = getDiscontiniousHistoricalStockBalanceStateTable(
            bookSelection, lastYear, optionalStockLabel);
    Table<Integer, Integer, Set<StockState>> continiousHistoricalStockBalanceStateTable = HashBasedTable
            .<Integer, Integer, Set<StockState>>create();
    List<Integer> yearsWithHistoricalValues = Lists
            .newArrayList(uncontiniousHistoricalStockBalanceStateTable.rowMap().keySet());
    Map<String, StockState> stockToStockState = new HashMap<String, StockState>();
    if (yearsWithHistoricalValues.size() > 0) {
        Collections.sort(yearsWithHistoricalValues);
        for (Integer currentYear = yearsWithHistoricalValues.get(0); currentYear <= lastYear; currentYear++) {
            Map<Integer, Set<StockState>> yearHistoricalStockBalanceStateTable = uncontiniousHistoricalStockBalanceStateTable
                    .rowMap().get(currentYear);
            for (Integer currentMonth = 0; currentMonth <= 11; currentMonth++) {
                Set<StockState> stockStateSet = new HashSet<StockState>();
                if (yearHistoricalStockBalanceStateTable != null
                        && yearHistoricalStockBalanceStateTable.get(currentMonth) != null) {
                    stockStateSet = yearHistoricalStockBalanceStateTable.get(currentMonth);
                }// w  w  w.ja  v a2  s  .  c  om
                Map<String, StockState> currentStockToStockState = Maps.uniqueIndex(stockStateSet,
                        new Function<StockState, String>() {
                            @Override
                            public String apply(StockState input) {
                                return input.getSymbol();
                            }
                        });
                stockToStockState.putAll(currentStockToStockState);
                continiousHistoricalStockBalanceStateTable.put(currentYear, currentMonth,
                        Sets.newHashSet(stockToStockState.values()));
            }
        }
    }
    return continiousHistoricalStockBalanceStateTable;
}

From source file:com.google.caja.plugin.BrowserTestCatalog.java

public BrowserTestCatalog(URL url) throws IOException {
    String json = Resources.toString(url, Charsets.UTF_8);
    List<Entry> entriesAcc = new ArrayList<Entry>();
    RhinoTestBed.runJs(new ParserOutput(entriesAcc),
            new Executor.Input(BrowserTestCatalog.class, "catalog-parser.js"),
            new Executor.Input("parseTestCatalog(" + json + ", caja___, true)", "<BrowserTestCatalog stub>"));
    entries = Collections.unmodifiableList(entriesAcc);
    entriesByLabel = Maps.uniqueIndex(entries, new Function<Entry, String>() {
        @Override/*from  www. j a  v  a2s.c  o m*/
        public String apply(Entry entry) {
            return entry.getLabel();
        }
    });
}

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

@Override
public Map<String, HostNameBinding> getHostNameBindings() {
    List<HostNameBindingInner> collectionInner = this.manager().inner().webApps()
            .listHostNameBindingsSlot(resourceGroupName(), this.parent().name(), name());
    List<HostNameBinding> hostNameBindings = new ArrayList<>();
    for (HostNameBindingInner inner : collectionInner) {
        hostNameBindings.add(new HostNameBindingImpl<>(inner, this));
    }// w w  w . j ava  2s. c om
    return Maps.uniqueIndex(hostNameBindings, new Function<HostNameBinding, String>() {
        @Override
        public String apply(HostNameBinding input) {
            return input.name().replace(name() + "/", "");
        }
    });
}

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

public void addProcedures(ConnectorId connectorId, Collection<Procedure> procedures) {
    requireNonNull(connectorId, "connectorId is null");
    requireNonNull(procedures, "procedures is null");

    procedures.forEach(this::validateProcedure);

    Map<SchemaTableName, Procedure> proceduresByName = Maps.uniqueIndex(procedures,
            procedure -> new SchemaTableName(procedure.getSchema(), procedure.getName()));

    checkState(connectorProcedures.putIfAbsent(connectorId, proceduresByName) == null,
            "Procedures already registered for connector: %s", connectorId);
}

From source file:org.jclouds.internal.FilterStringsBoundToInjectorByName.java

@Override
public Map<String, String> apply(Predicate<String> filter) {
    List<Binding<String>> stringBindings = injector.findBindingsByType(TypeLiteral.get(String.class));
    Iterable<Binding<String>> annotatedWithName = Iterables.filter(stringBindings,
            new Predicate<Binding<String>>() {

                @Override//from  w  ww .  j  a v a 2  s. c  om
                public boolean apply(Binding<String> input) {
                    Annotation annotation = input.getKey().getAnnotation();
                    if (annotation == null)
                        return false;
                    return (annotation instanceof javax.inject.Named)
                            || (annotation instanceof com.google.inject.name.Named);
                }

            });

    Map<String, Binding<String>> bindingsByName = Maps.uniqueIndex(annotatedWithName,
            new Function<Binding<String>, String>() {

                @Override
                public String apply(Binding<String> input) {
                    Annotation annotation = input.getKey().getAnnotation();
                    return (annotation instanceof javax.inject.Named)
                            ? javax.inject.Named.class.cast(annotation).value()
                            : com.google.inject.name.Named.class.cast(annotation).value();
                }

            });

    Map<String, Binding<String>> filteredBindingsByName = Maps.filterKeys(bindingsByName, filter);

    Map<String, String> stringBoundByName = Maps.transformValues(filteredBindingsByName,
            new Function<Binding<String>, String>() {

                @Override
                public String apply(Binding<String> input) {
                    return input.getProvider().get();
                }
            });
    return stringBoundByName;
}

From source file:com.isotrol.impe3.pms.core.support.PortalComponents.java

/**
 * Constructor
 * @param components Component definitions.
 */
private PortalComponents(Iterable<ComponentDfn> components) {
    map = Maps.uniqueIndex(components, DFN2ID);
}

From source file:com.arpnetworking.tsdcore.sinks.LimitingSink.java

/**
 * {@inheritDoc}/*from w w w. jav  a 2s. c o  m*/
 */
@Override
public void recordAggregateData(final Collection<AggregatedData> data, final Collection<Condition> conditions) {
    final DateTime now = DateTime.now();
    final List<AggregatedData> filteredData = Lists.newArrayListWithExpectedSize(data.size());
    final Map<FQDSN, Condition> conditionsByFQDSN = Maps.uniqueIndex(conditions,
            new Function<Condition, FQDSN>() {
                @Override
                public FQDSN apply(final Condition condition) {
                    return condition.getFQDSN();
                }
            });
    long limited = 0;
    for (final AggregatedData datum : data) {
        if (_metricsLimiter.offer(datum, now)) {
            filteredData.add(datum);
        } else {
            LOGGER.warn(String.format("%s: Skipping publication of limited data; aggregatedData=%s", getName(),
                    datum));
            ++limited;

            // Remove any condition for the FQDSN
            // NOTE: Although limiting also contains period, the data produced
            // in any one invocation of the sink is for a single period we can
            // safely ignore that and find any matching conditions by FQDSN.
            conditionsByFQDSN.remove(datum.getFQDSN());
        }
    }
    _limited.getAndAdd(limited);
    _sink.recordAggregateData(filteredData, conditionsByFQDSN.values());
}

From source file:com.facebook.buck.android.resources.ResourceTable.java

public static ResourceTable slice(ResourceTable table, Map<Integer, Integer> countsToExtract) {
    ResTablePackage newPackage = ResTablePackage.slice(table.resPackage, countsToExtract);

    StringPool strings = table.strings;//w ww .  ja  v a  2s .  c o  m
    // Figure out what strings are used by the retained references.
    ImmutableSortedSet.Builder<Integer> stringRefs = ImmutableSortedSet
            .orderedBy(Comparator.comparing(strings::getString).thenComparingInt(i -> i));
    newPackage.visitStringReferences(stringRefs::add);
    ImmutableList<Integer> stringsToExtract = stringRefs.build().asList();
    ImmutableMap<Integer, Integer> stringMapping = Maps
            .uniqueIndex(IntStream.range(0, stringsToExtract.size())::iterator, stringsToExtract::get);

    // Extract a StringPool that contains just the strings used by the new package.
    // This drops styles.
    StringPool newStrings = StringPool.create(stringsToExtract.stream().map(strings::getString)::iterator);

    // Adjust the string references.
    newPackage.transformStringReferences(stringMapping::get);

    return new ResourceTable(newStrings, newPackage);
}