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

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

Introduction

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

Prototype

public static <K, V> ImmutableMap<K, V> toMap(Iterator<K> keys, Function<? super K, V> valueFunction) 

Source Link

Document

Returns an immutable map whose keys are the distinct elements of keys and whose value for each key was computed by valueFunction .

Usage

From source file:org.onosproject.store.consistent.impl.DistributedLeadershipManager.java

@Override
public Map<String, List<NodeId>> getCandidates() {
    return Maps.toMap(candidateBoard.keySet(), this::getCandidates);
}

From source file:edu.mit.streamjit.impl.compiler2.ActorGroup.java

/**
 * Returns a map mapping each output Storage to the set of physical indices
 * written in that Storage during the given ActorGroup iteration.
 * @param iteration the iteration to simulate
 * @return a map of written physical indices
 *///from  w  w  w .  j a  v  a 2s  .c o m
public ImmutableMap<Storage, ImmutableSortedSet<Integer>> writes(final int iteration) {
    return Maps.toMap(outputs(), (Storage output) -> writes(output, iteration));
}

From source file:google.registry.flows.FlowTestCase.java

/**
 * Assert that the actual grace periods and the corresponding billing events referenced from
 * their keys match the expected map of grace periods to billing events.  For the expected map,
 * the keys on the grace periods and IDs on the billing events are ignored.
 */// w  w w  . j  a  va2  s  .c  o m
public void assertGracePeriods(Iterable<GracePeriod> actual,
        ImmutableMap<GracePeriod, ? extends BillingEvent> expected) {
    Function<GracePeriod, BillingEvent> gracePeriodExpander = new Function<GracePeriod, BillingEvent>() {
        @Override
        public BillingEvent apply(GracePeriod gracePeriod) {
            assertThat(gracePeriod.hasBillingEvent())
                    .named("Billing event is present for grace period: " + gracePeriod).isTrue();
            return ofy().load().key(
                    firstNonNull(gracePeriod.getOneTimeBillingEvent(), gracePeriod.getRecurringBillingEvent()))
                    .now();
        }
    };
    assertThat(canonicalizeGracePeriods(Maps.toMap(actual, gracePeriodExpander)))
            .isEqualTo(canonicalizeGracePeriods(expected));
}

From source file:ezbake.deployer.utilities.PackageDeployer.java

private static Map<File, String> getConfigFileNames(Iterable<File> configFiles) {
    return Maps.toMap(configFiles, new Function<File, String>() {
        @Override/*  w  ww.ja v  a2 s .c  o  m*/
        public String apply(File file) {
            return file.getName();
        }
    });
}

From source file:org.calrissian.mango.collect.FluentCloseableIterable.java

/**
 * Returns an immutable map for which the elements of this {@code FluentIterable} are the keys in
 * the same order, mapped to values by the given function. If this iterable contains duplicate
 * elements, the returned map will contain each distinct element once in the order it first
 * appears.//from   ww w .ja  v a 2  s .co m
 *
 * @throws NullPointerException if any element of this iterable is {@code null}, or if {@code
 *     valueFunction} produces {@code null} for any key
 */
public final <V> ImmutableMap<T, V> toMap(Function<? super T, V> valueFunction) {
    return Maps.toMap(this, valueFunction);
}

From source file:org.apache.hadoop.hive.kafka.KafkaScanTrimmer.java

@Nullable
private static Map<TopicPartition, KafkaInputSplit> buildScanForTimesPredicate(
        Map<TopicPartition, KafkaInputSplit> fullHouse, PredicateLeaf.Operator operator, long timestamp,
        boolean flip, boolean negation, KafkaConsumer<byte[], byte[]> consumer) {
    long increment = (flip && operator == PredicateLeaf.Operator.LESS_THAN
            || negation && operator == PredicateLeaf.Operator.LESS_THAN_EQUALS) ? 1L : 0L;
    // only accepted cases are timestamp_column [ > ; >= ; = ]constant
    if (operator == PredicateLeaf.Operator.EQUALS || flip ^ negation) {
        final Map<TopicPartition, Long> timePartitionsMap = Maps.toMap(fullHouse.keySet(),
                tp -> timestamp + increment);
        try {//from  w ww  . ja  va  2 s .c o m
            // Based on Kafka docs
            // NULL will be returned for that partition If the message format version in a partition is before 0.10.0
            Map<TopicPartition, OffsetAndTimestamp> offsetAndTimestamp = consumer
                    .offsetsForTimes(timePartitionsMap);
            return Maps.toMap(fullHouse.keySet(), tp -> {
                KafkaInputSplit existing = fullHouse.get(tp);
                OffsetAndTimestamp foundOffsetAndTime = offsetAndTimestamp.get(tp);
                //Null in case filter doesn't match or field not existing ie old broker thus return empty scan.
                final long startOffset = foundOffsetAndTime == null ? existing.getEndOffset()
                        : foundOffsetAndTime.offset();
                return new KafkaInputSplit(Objects.requireNonNull(tp).topic(), tp.partition(), startOffset,
                        existing.getEndOffset(), existing.getPath());
            });
        } catch (Exception e) {
            LOG.error("Error while looking up offsets for time", e);
            //Bailout when can not figure out offsets for times.
            return null;
        }

    }
    return null;
}

From source file:org.immutables.sequence.Sequence.java

/**
 * Returns an immutable map for which the elements of this {@code Sequence} are the keys in
 * the same order, mapped to values by the given function. If this iterable contains duplicate
 * elements, the returned map will contain each distinct element once in the order it first
 * appears.// ww w . j av  a 2 s.  c o m
 * @param <V> the value type
 * @param valueFunction the value function
 * @return the immutable map
 * @since 14.0
 */
public final <V> ImmutableMap<E, V> toMap(Function<? super E, V> valueFunction) {
    return Maps.toMap(iterable, valueFunction::apply);
}

From source file:com.palantir.atlasdb.transaction.impl.SerializableTransaction.java

private void verifyCells(Transaction ro) {
    for (String table : cellsRead.keySet()) {
        final ConcurrentNavigableMap<Cell, byte[]> readsForTable = getReadsForTable(table);
        for (Iterable<Cell> batch : Iterables.partition(cellsRead.get(table), 1000)) {
            if (writesByTable.get(table) != null) {
                // We don't want to verify any reads that we wrote to cause we will just read our own values.
                // NB: If the value has changed between read and write, our normal SI checking handles this case
                batch = Iterables.filter(batch,
                        Predicates.not(Predicates.in(writesByTable.get(table).keySet())));
            }/*from  ww w. j a v  a  2s . c o  m*/
            ImmutableSet<Cell> batchSet = ImmutableSet.copyOf(batch);
            Map<Cell, byte[]> currentBatch = ro.get(table, batchSet);
            ImmutableMap<Cell, byte[]> originalReads = Maps.toMap(
                    Sets.intersection(batchSet, readsForTable.keySet()), Functions.forMap(readsForTable));
            if (!areMapsEqual(currentBatch, originalReads)) {
                throw TransactionSerializableConflictException.create(table, getTimestamp(),
                        System.currentTimeMillis() - timeCreated);
            }
        }
    }
}

From source file:io.prestosql.plugin.raptor.legacy.metadata.DatabaseShardManager.java

private Map<String, Integer> toNodeIdMap(Collection<ShardInfo> shards) {
    Set<String> identifiers = shards.stream().map(ShardInfo::getNodeIdentifiers).flatMap(Collection::stream)
            .collect(toSet());/*  w ww . j  av  a2  s  .  c o m*/
    return Maps.toMap(identifiers, this::getOrCreateNodeId);
}

From source file:com.googlecode.blaisemath.sketch.SketchActions.java

public static void alignHorizontal(Set<Graphic<Graphics2D>> selection) {
    Iterable<Graphic<Graphics2D>> sub = Iterables.filter(selection, MOVABLE_PREDICATE);
    if (Iterables.size(sub) < 2) {
        Logger.getLogger(SketchActions.class.getName()).log(Level.INFO,
                "Cannot align with fewer than 2 movable predicates.");
        return;/*from www. j  a va  2 s . co m*/
    }
    ImmutableMap<Graphic<Graphics2D>, Point2D> locs = Maps.toMap(sub, LOC_FUNCTION);
    double yAvg = Points.average(locs.values()).getY();
    for (Graphic<Graphics2D> gr : sub) {
        setPrimitiveLocation((PrimitiveGraphicSupport<?, Graphics2D>) gr,
                new Point2D.Double(locs.get(gr).getX(), yAvg));
    }
}