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

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

Introduction

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

Prototype

@GwtIncompatible("NavigableMap")
public static <K, V1, V2> NavigableMap<K, V2> transformValues(NavigableMap<K, V1> fromMap,
        Function<? super V1, V2> function) 

Source Link

Document

Returns a view of a navigable map where each value is transformed by a function.

Usage

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

/**
 * Creates a new map with the results of a value transformation.
 * @param <K> Key type.//from   w ww  .  jav  a2s .  co  m
 * @param <V1> Original value type.
 * @param <V2> Transformed value type.
 * @param from Original map.
 * @param function Transformation function.
 * @return The transformed map.
 */
public static <K, V1, V2> Map<K, V2> map(Map<K, V1> from, Function<? super V1, ? extends V2> function) {
    return Maps.newHashMap(Maps.transformValues(from, function));
}

From source file:google.registry.tools.server.ListObjectsAction.java

/**
 * Returns a table of data for the given sets of fields and objects.  The table is row-keyed by
 * object and column-keyed by field, in the same iteration order as the provided sets.
 *///from www. j  av a2 s .c o m
private ImmutableTable<T, String, String> extractData(ImmutableSet<String> fields, ImmutableSet<T> objects) {
    ImmutableTable.Builder<T, String, String> builder = new ImmutableTable.Builder<>();
    for (T object : objects) {
        Map<String, Object> fieldMap = new HashMap<>();
        // Base case of the mapping is to use ImmutableObject's toDiffableFieldMap().
        fieldMap.putAll(object.toDiffableFieldMap());
        // Next, overlay any field-level overrides specified by the subclass.
        fieldMap.putAll(getFieldOverrides(object));
        // Next, add to the mapping all the aliases, with their values defined as whatever was in the
        // map under the aliased field's original name.
        fieldMap.putAll(Maps.transformValues(getFieldAliases(), Functions.forMap(new HashMap<>(fieldMap))));
        Set<String> expectedFields = ImmutableSortedSet.copyOf(fieldMap.keySet());
        for (String field : fields) {
            checkArgument(fieldMap.containsKey(field), "Field '%s' not found - recognized fields are:\n%s",
                    field, expectedFields);
            builder.put(object, field, Objects.toString(fieldMap.get(field), ""));
        }
    }
    return builder.build();
}

From source file:com.splicemachine.orc.OrcRecordReader.java

public OrcRecordReader(Map<Integer, DataType> includedColumns, OrcPredicate predicate, long numberOfRows,
        List<StripeInformation> fileStripes, List<ColumnStatistics> fileStats,
        List<StripeStatistics> stripeStats, OrcDataSource orcDataSource, long splitOffset, long splitLength,
        List<OrcType> types, CompressionKind compressionKind, int bufferSize, int rowsInRowGroup,
        DateTimeZone hiveStorageTimeZone, HiveWriterVersion hiveWriterVersion, MetadataReader metadataReader,
        DataSize maxMergeDistance, DataSize maxReadSize, Map<String, Slice> userMetadata,
        AbstractAggregatedMemoryContext systemMemoryUsage, List<Integer> partitionIds,
        List<String> partitionValues) throws IOException {
    requireNonNull(includedColumns, "includedColumns is null");
    requireNonNull(predicate, "predicate is null");
    requireNonNull(fileStripes, "fileStripes is null");
    requireNonNull(stripeStats, "stripeStats is null");
    requireNonNull(orcDataSource, "orcDataSource is null");
    requireNonNull(types, "types is null");
    requireNonNull(compressionKind, "compressionKind is null");
    requireNonNull(hiveStorageTimeZone, "hiveStorageTimeZone is null");
    requireNonNull(userMetadata, "userMetadata is null");

    // Place to add static values?

    // Adding All Included Columns
    this.includedColumns = includedColumns;

    this.partitionValues = partitionValues;
    this.partitionIds = partitionIds;

    // reduce the included columns to the set that is also present
    presentColumns = new TreeSet<>();
    Map<Integer, DataType> presentColumnsAndTypes = new TreeMap();

    OrcType root = types.get(0);//w  w  w.j a va2s  .  com
    int partitionDecrement = 0;
    for (Map.Entry<Integer, DataType> entry : includedColumns.entrySet()) {
        entry.getKey();
        // an old file can have less columns since columns can be added
        // after the file was written
        if (partitionIds.contains(entry.getKey()) || entry.getKey() >= root.getFieldCount()) {
            // ignore for now
        } else {
            presentColumns.add(entry.getKey() - partitionDecrement);
            presentColumnsAndTypes.put(entry.getKey() - partitionDecrement, entry.getValue());
        }
    }

    // it is possible that old versions of orc use 0 to mean there are no row groups
    checkArgument(rowsInRowGroup > 0, "rowsInRowGroup must be greater than zero");

    // sort stripes by file position
    List<StripeInfo> stripeInfos = new ArrayList<>();
    for (int i = 0; i < fileStripes.size(); i++) {
        Optional<StripeStatistics> stats = Optional.empty();
        // ignore all stripe stats if too few or too many
        if (stripeStats.size() == fileStripes.size()) {
            stats = Optional.of(stripeStats.get(i));
        }
        stripeInfos.add(new StripeInfo(fileStripes.get(i), stats));
    }
    Collections.sort(stripeInfos, comparingLong(info -> info.getStripe().getOffset()));

    long totalRowCount = 0;
    long fileRowCount = 0;
    ImmutableList.Builder<StripeInformation> stripes = ImmutableList.builder();
    ImmutableList.Builder<Long> stripeFilePositions = ImmutableList.builder();
    if (predicate.matches(numberOfRows, getStatisticsByColumnOrdinal(root, fileStats))) {
        // select stripes that start within the specified split
        for (StripeInfo info : stripeInfos) {
            StripeInformation stripe = info.getStripe();
            if (splitContainsStripe(splitOffset, splitLength, stripe)
                    && isStripeIncluded(root, stripe, info.getStats(), predicate)) {
                stripes.add(stripe);
                stripeFilePositions.add(fileRowCount);
                totalRowCount += stripe.getNumberOfRows();
            }
            fileRowCount += stripe.getNumberOfRows();
        }
    }
    this.totalRowCount = totalRowCount;
    this.stripes = stripes.build();
    this.stripeFilePositions = stripeFilePositions.build();

    orcDataSource = wrapWithCacheIfTinyStripes(orcDataSource, this.stripes, maxMergeDistance, maxReadSize);
    this.orcDataSource = orcDataSource;
    this.splitLength = splitLength;

    this.fileRowCount = stripeInfos.stream().map(StripeInfo::getStripe)
            .mapToLong(StripeInformation::getNumberOfRows).sum();

    this.userMetadata = ImmutableMap.copyOf(Maps.transformValues(userMetadata, Slices::copyOf));

    this.systemMemoryUsage = requireNonNull(systemMemoryUsage, "systemMemoryUsage is null")
            .newAggregatedMemoryContext();
    this.currentStripeSystemMemoryContext = systemMemoryUsage.newAggregatedMemoryContext();

    stripeReader = new StripeReader(orcDataSource, compressionKind, types, bufferSize, this.presentColumns,
            rowsInRowGroup, predicate, hiveWriterVersion, metadataReader);

    streamReaders = createStreamReaders(orcDataSource, types, hiveStorageTimeZone, presentColumnsAndTypes);
}

From source file:com.turn.ttorrent.client.SwarmHandler.java

@Override
public Map<? extends SocketAddress, ? extends byte[]> getPeers() {
    return Maps.transformValues(knownPeers, new Function<PeerInformation, byte[]>() {
        @Override/*from  ww  w  .j  a  v  a  2  s  .c o m*/
        public byte[] apply(PeerInformation input) {
            return input.remotePeerId;
        }
    });
}

From source file:org.apache.druid.server.router.TieredBrokerHostSelector.java

public Map<String, List<Server>> getAllBrokers() {
    return Maps.transformValues(servers, new Function<NodesHolder, List<Server>>() {
        @Override//from  ww  w  .  j a v a 2 s  . com
        public List<Server> apply(NodesHolder input) {
            return input.getAll();
        }
    });
}

From source file:org.estatio.webapp.shiro.EstatioLdapRealm.java

public void setRoleListByGroup(Map<String, String> roleListStrByGroup) {
    Map<String, List<String>> roleListByGroup = Maps.transformValues(roleListStrByGroup, splitOn('|'));
    this.roleListByGroup.putAll(roleListByGroup);
}

From source file:ninja.leaping.permissionsex.backend.memory.MemorySubjectData.java

@Override
public ImmutableSubjectData clearOptions() {
    if (this.contexts.isEmpty()) {
        return this;
    }/*from  w  w w .j a v a 2s. c  o m*/

    Map<Set<Entry<String, String>>, DataEntry> newValue = Maps.transformValues(this.contexts,
            dataEntry -> dataEntry == null ? null : dataEntry.withoutOptions());
    return newData(newValue);
}

From source file:com.facebook.buck.android.relinker.NativeRelinker.java

public NativeRelinker(BuildRuleParams buildRuleParams, SourcePathResolver resolver,
        SourcePathRuleFinder ruleFinder, CxxBuckConfig cxxBuckConfig,
        ImmutableMap<TargetCpuType, NdkCxxPlatform> nativePlatforms,
        ImmutableMap<Pair<TargetCpuType, String>, SourcePath> linkableLibs,
        ImmutableMap<Pair<TargetCpuType, String>, SourcePath> linkableLibsAssets) {
    this.ruleFinder = ruleFinder;
    Preconditions.checkArgument(!linkableLibs.isEmpty() || !linkableLibsAssets.isEmpty(),
            "There should be at least one native library to relink.");

    this.buildRuleParams = buildRuleParams;
    this.resolver = resolver;
    this.cxxBuckConfig = cxxBuckConfig;
    this.nativePlatforms = nativePlatforms;

    /*//from  w  ww  .j  ava 2s . c o m
    When relinking a library, any symbols needed by a (transitive) dependent must continue to be
    exported. As relinking one of those dependents may change the set of symbols that it needs,
    we only need to keep the symbols that are still used after a library is relinked. So, this
    relinking process basically works in the reverse order of the original link process. As each
    library is relinked, we now know the set of symbols that are needed in that library's
    dependencies.
            
    For linkables that can't be resolved to a BuildRule, we can't tell what libraries that one
    depends on. So, we essentially assume that everything depends on it.
    */

    ImmutableMap.Builder<BuildRule, Pair<TargetCpuType, SourcePath>> ruleMapBuilder = ImmutableMap.builder();
    ImmutableSet.Builder<Pair<TargetCpuType, SourcePath>> copiedLibraries = ImmutableSet.builder();

    for (Map.Entry<Pair<TargetCpuType, String>, SourcePath> entry : Iterables.concat(linkableLibs.entrySet(),
            linkableLibsAssets.entrySet())) {
        SourcePath source = entry.getValue();
        Optional<BuildRule> rule = ruleFinder.getRule(source);
        if (rule.isPresent()) {
            ruleMapBuilder.put(rule.get(), new Pair<>(entry.getKey().getFirst(), source));
        } else {
            copiedLibraries.add(new Pair<>(entry.getKey().getFirst(), source));
        }
    }

    ImmutableMap<BuildRule, Pair<TargetCpuType, SourcePath>> ruleMap = ruleMapBuilder.build();
    ImmutableSet<BuildRule> linkableRules = ruleMap.keySet();

    // Now, for every linkable build rule, we need to figure out all the other linkable build rules
    // that could depend on it (or rather, could use symbols from it).

    // This is the sub-graph that includes the linkableRules and all the dependents (including
    // non-linkable rules).
    final DirectedAcyclicGraph<BuildRule> graph = getBuildGraph(linkableRules);
    ImmutableList<BuildRule> sortedRules = TopologicalSort.sort(graph);
    // This maps a build rule to every rule in linkableRules that depends on it. This (added to the
    // copied libraries) is the set of linkables that could use a symbol from this build rule.
    ImmutableMap<BuildRule, ImmutableSet<BuildRule>> allDependentsMap = getAllDependentsMap(linkableRules,
            graph, sortedRules);

    ImmutableMap.Builder<SourcePath, SourcePath> pathMap = ImmutableMap.builder();

    // Create the relinker rules for the libraries that couldn't be resolved back to a base rule.
    ImmutableList.Builder<RelinkerRule> relinkRules = ImmutableList.builder();
    for (Pair<TargetCpuType, SourcePath> p : copiedLibraries.build()) {
        // TODO(cjhopman): We shouldn't really need a full RelinkerRule at this point. We know that we
        // are just going to copy it, we could just leave these libraries in place and only calculate
        // the list of needed symbols.
        TargetCpuType cpuType = p.getFirst();
        SourcePath source = p.getSecond();
        RelinkerRule relink = makeRelinkerRule(cpuType, source, ImmutableList.of());
        relinkRules.add(relink);
        pathMap.put(source, relink.getLibFileSourcePath());
    }
    ImmutableList<RelinkerRule> copiedLibrariesRules = relinkRules.build();

    // Process the remaining linkable rules in the reverse sorted order. This makes it easy to refer
    // to the RelinkerRules of dependents.
    Iterable<Pair<TargetCpuType, SourcePath>> sortedPaths = FluentIterable.from(sortedRules)
            .filter(linkableRules::contains).transform(Functions.forMap(ruleMap)).toList().reverse();
    Map<BuildRule, RelinkerRule> relinkerMap = new HashMap<>();

    for (Pair<TargetCpuType, SourcePath> p : sortedPaths) {
        TargetCpuType cpuType = p.getFirst();
        SourcePath source = p.getSecond();
        BuildRule baseRule = ruleFinder.getRuleOrThrow((BuildTargetSourcePath) source);
        // Relinking this library must keep any of the symbols needed by the libraries from the rules
        // in relinkerDeps.
        ImmutableList<RelinkerRule> relinkerDeps = ImmutableList.<RelinkerRule>builder()
                .addAll(copiedLibrariesRules)
                .addAll(Lists.transform(ImmutableList.copyOf(allDependentsMap.get(baseRule)),
                        Functions.forMap(relinkerMap)))
                .build();

        RelinkerRule relink = makeRelinkerRule(cpuType, source, relinkerDeps);
        relinkRules.add(relink);
        pathMap.put(source, relink.getLibFileSourcePath());
        relinkerMap.put(baseRule, relink);
    }

    Function<SourcePath, SourcePath> pathMapper = Functions.forMap(pathMap.build());
    rules = relinkRules.build();
    relinkedLibs = ImmutableMap.copyOf(Maps.transformValues(linkableLibs, pathMapper));
    relinkedLibsAssets = ImmutableMap.copyOf(Maps.transformValues(linkableLibsAssets, pathMapper));
}

From source file:com.facebook.buck.util.cache.impl.LimitedFileHashCacheEngine.java

@Override
public ConcurrentMap<Path, HashCodeAndFileType> asMap() {
    return new ConcurrentHashMap<>(Maps.transformValues(fileSystemMap.asMap(),
            v -> Objects.requireNonNull(v).getHashCodeAndFileType()));
}

From source file:com.qcadoo.mes.deviationCausesReporting.print.DeviationsProtocolPdf.java

private VerticalLayout createDetailedSummarySection(final DeviationsReportCriteria criteria,
        final Locale locale) {
    Multimap<String, DeviationSummary> summariesByType = deviationSummariesDataProvider
            .getDeviationsByCauseType(criteria);
    if (summariesByType.isEmpty()) {
        return VerticalLayout.empty();
    }/* ww w  .  j  av  a2s . c  o  m*/
    Map<String, PdfPTable> deviationCausesWithSummary = Maps.transformValues(summariesByType.asMap(),
            getSummariesToTableConverter(locale));
    List<VerticalLayout> causeAndSummaryLayouts = FluentIterable.from(deviationCausesWithSummary.entrySet())
            .transform(CAUSE_AND_SUMMARY_TABLE_IN_VERTICAL_LAYOUT).toList();
    VerticalLayout tables = Fold.fold(causeAndSummaryLayouts, VerticalLayout.create(),
            VerticalLayout.REDUCE_BY_MERGE);
    Paragraph header = Headers
            .big(translate("deviationCausesReporting.report.deviationDetailsByType.header", locale));
    return VerticalLayout.create().append(header).merge(tables);
}