Java Code Examples for java.util.function.ToIntFunction#applyAsInt()

The following examples show how to use java.util.function.ToIntFunction#applyAsInt() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: Tile.java    From freecol with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Sort possible goods types according to potential.
 *
 * @param unitType The {@code UnitType} to do the work.
 * @param owner the {@code Player} owning the unit.
 * @return A list of goods, highest potential production first.
 */
public List<AbstractGoods> getSortedPotential(UnitType unitType,
                                              Player owner) {
    // Defend against calls while partially read.
    if (getType() == null) return Collections.<AbstractGoods>emptyList();
    
    final ToIntFunction<GoodsType> productionMapper = cacheInt(gt ->
        getPotentialProduction(gt, unitType));
    final Predicate<GoodsType> productionPred = gt ->
        productionMapper.applyAsInt(gt) > 0;
    final Function<GoodsType, AbstractGoods> goodsMapper = gt ->
        new AbstractGoods(gt, productionMapper.applyAsInt(gt));
    final Comparator<AbstractGoods> goodsComp
        = ((owner == null || owner.getMarket() == null)
            ? AbstractGoods.descendingAmountComparator
            : owner.getMarket().getSalePriceComparator());
    // It is necessary to consider all farmed goods, since the
    // tile might have a resource that produces goods not produced
    // by the tile type.
    return transform(getSpecification().getFarmedGoodsTypeList(),
                     productionPred, goodsMapper, goodsComp);
}
 
Example 2
Source File: TestDriftNettyServerTransport.java    From drift with Apache License 2.0 6 votes vote down vote up
private static int testServerMethodInvoker(ServerMethodInvoker methodInvoker, boolean assumeClientsSupportOutOfOrderResponses, List<ToIntFunction<HostAndPort>> clients)
{
    DriftNettyServerConfig config = new DriftNettyServerConfig()
            .setAssumeClientsSupportOutOfOrderResponses(assumeClientsSupportOutOfOrderResponses);
    TestingPooledByteBufAllocator testingAllocator = new TestingPooledByteBufAllocator();
    ServerTransport serverTransport = new DriftNettyServerTransportFactory(config, testingAllocator).createServerTransport(methodInvoker);
    try {
        serverTransport.start();

        HostAndPort address = HostAndPort.fromParts("localhost", ((DriftNettyServerTransport) serverTransport).getPort());

        int sum = 0;
        for (ToIntFunction<HostAndPort> client : clients) {
            sum += client.applyAsInt(address);
        }
        return sum;
    }
    finally {
        serverTransport.shutdown();
        testingAllocator.close();
    }
}
 
Example 3
Source File: CollectionHelper.java    From customstuff4 with GNU General Public License v3.0 6 votes vote down vote up
/**
 * Gets a random element from the given collection where each element has a weight provided by weightFunction.
 * A higher weight makes an element more likely to be selected.
 *
 * @return A random element or null if the collection was empty.
 */
@Nonnull
public static <T> Optional<T> randomElement(Collection<T> collection, ToIntFunction<T> weightFunction)
{
    int totalWeight = collection.stream().mapToInt(weightFunction).sum();
    int randomWeight = RandomUtils.nextInt(1, totalWeight + 1);

    for (T t : collection)
    {
        randomWeight -= weightFunction.applyAsInt(t);
        if (randomWeight <= 0)
            return Optional.of(t);
    }

    return Optional.empty();
}
 
Example 4
Source File: TestDriftNettyMethodInvoker.java    From drift with Apache License 2.0 6 votes vote down vote up
private static int testMethodInvoker(ServerMethodInvoker methodInvoker, List<ToIntFunction<HostAndPort>> clients)
{
    TestingPooledByteBufAllocator testingAllocator = new TestingPooledByteBufAllocator();
    ServerTransport serverTransport = new DriftNettyServerTransportFactory(new DriftNettyServerConfig(), testingAllocator).createServerTransport(methodInvoker);
    try {
        serverTransport.start();

        HostAndPort address = HostAndPort.fromParts("localhost", ((DriftNettyServerTransport) serverTransport).getPort());

        int sum = 0;
        for (ToIntFunction<HostAndPort> client : clients) {
            sum += client.applyAsInt(address);
        }
        return sum;
    }
    finally {
        serverTransport.shutdown();
        testingAllocator.close();
    }
}
 
Example 5
Source File: TestClientsWithDriftNettyServerTransport.java    From drift with Apache License 2.0 6 votes vote down vote up
private static int testDriftServer(ServerMethodInvoker methodInvoker, List<ToIntFunction<HostAndPort>> clients)
{
    DriftNettyServerConfig config = new DriftNettyServerConfig()
            .setSslEnabled(true)
            .setTrustCertificate(ClientTestUtils.getCertificateChainFile())
            .setKey(ClientTestUtils.getPrivateKeyFile());
    TestingPooledByteBufAllocator testingAllocator = new TestingPooledByteBufAllocator();
    ServerTransport serverTransport = new DriftNettyServerTransportFactory(config, testingAllocator).createServerTransport(methodInvoker);
    try {
        serverTransport.start();

        HostAndPort address = HostAndPort.fromParts("localhost", ((DriftNettyServerTransport) serverTransport).getPort());

        int sum = 0;
        for (ToIntFunction<HostAndPort> client : clients) {
            sum += client.applyAsInt(address);
        }
        return sum;
    }
    finally {
        serverTransport.shutdown();
        testingAllocator.close();
    }
}
 
Example 6
Source File: NodePartitioningManager.java    From presto with Apache License 2.0 6 votes vote down vote up
private ToIntFunction<Split> getSplitToBucket(Session session, PartitioningHandle partitioningHandle)
{
    ConnectorNodePartitioningProvider partitioningProvider = partitioningProviders.get(partitioningHandle.getConnectorId().get());
    checkArgument(partitioningProvider != null, "No partitioning provider for connector %s", partitioningHandle.getConnectorId().get());

    ToIntFunction<ConnectorSplit> splitBucketFunction = partitioningProvider.getSplitBucketFunction(
            partitioningHandle.getTransactionHandle().orElse(null),
            session.toConnectorSession(),
            partitioningHandle.getConnectorHandle());
    checkArgument(splitBucketFunction != null, "No partitioning %s", partitioningHandle);

    return split -> {
        int bucket;
        if (split.getConnectorSplit() instanceof EmptySplit) {
            bucket = split.getLifespan().isTaskWide() ? 0 : split.getLifespan().getId();
        }
        else {
            bucket = splitBucketFunction.applyAsInt(split.getConnectorSplit());
        }
        if (!split.getLifespan().isTaskWide()) {
            checkArgument(split.getLifespan().getId() == bucket);
        }
        return bucket;
    };
}
 
Example 7
Source File: TestApacheThriftMethodInvoker.java    From drift with Apache License 2.0 5 votes vote down vote up
private static int testProcessor(TProcessor processor, List<ToIntFunction<HostAndPort>> clients)
        throws Exception
{
    try (TServerSocket serverTransport = new TServerSocket(0)) {
        TProtocolFactory protocolFactory = new Factory();
        TTransportFactory transportFactory = new TFramedTransport.Factory();
        TServer server = new TSimpleServer(new Args(serverTransport)
                .protocolFactory(protocolFactory)
                .transportFactory(transportFactory)
                .processor(processor));

        Thread serverThread = new Thread(server::serve);
        try {
            serverThread.start();

            int localPort = serverTransport.getServerSocket().getLocalPort();
            HostAndPort address = HostAndPort.fromParts("localhost", localPort);

            int sum = 0;
            for (ToIntFunction<HostAndPort> client : clients) {
                sum += client.applyAsInt(address);
            }
            return sum;
        }
        finally {
            server.stop();
            serverThread.interrupt();
        }
    }
}
 
Example 8
Source File: Enchantments.java    From EnchantmentCracker with MIT License 5 votes vote down vote up
private static <T> T weightedRandom(Random rand, List<T> list, ToIntFunction<T> weightExtractor) {
	int weight = list.stream().mapToInt(weightExtractor).sum();
	if (weight <= 0) {
		return null;
	}
	weight = rand.nextInt(weight);
	for (T t : list) {
		weight -= weightExtractor.applyAsInt(t);
		if (weight < 0) {
			return t;
		}
	}
	return null;
}
 
Example 9
Source File: TestDriftNettyMethodInvoker.java    From drift with Apache License 2.0 5 votes vote down vote up
private static int testProcessor(TProcessor processor, List<ToIntFunction<HostAndPort>> clients)
        throws Exception
{
    try (TServerSocket serverTransport = new TServerSocket(0)) {
        TProtocolFactory protocolFactory = new TBinaryProtocol.Factory();
        TTransportFactory transportFactory = new TFramedTransport.Factory();
        TServer server = new TSimpleServer(new Args(serverTransport)
                .protocolFactory(protocolFactory)
                .transportFactory(transportFactory)
                .processor(processor));

        Thread serverThread = new Thread(server::serve);
        try {
            serverThread.start();

            int localPort = serverTransport.getServerSocket().getLocalPort();
            HostAndPort address = HostAndPort.fromParts("localhost", localPort);

            int sum = 0;
            for (ToIntFunction<HostAndPort> client : clients) {
                sum += client.applyAsInt(address);
            }
            return sum;
        }
        finally {
            server.stop();
            serverThread.interrupt();
        }
    }
}
 
Example 10
Source File: Collectors.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the sum of a integer-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Integer>
summingInt(ToIntFunction<? super T> mapper) {
    return new CollectorImpl<>(
            () -> new int[1],
            (a, t) -> { a[0] += mapper.applyAsInt(t); },
            (a, b) -> { a[0] += b[0]; return a; },
            a -> a[0], CH_NOID);
}
 
Example 11
Source File: Collectors.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the sum of a integer-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Integer>
summingInt(ToIntFunction<? super T> mapper) {
    return new CollectorImpl<>(
            () -> new int[1],
            (a, t) -> { a[0] += mapper.applyAsInt(t); },
            (a, b) -> { a[0] += b[0]; return a; },
            a -> a[0], CH_NOID);
}
 
Example 12
Source File: Collectors.java    From TencentKona-8 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the sum of a integer-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Integer>
summingInt(ToIntFunction<? super T> mapper) {
    return new CollectorImpl<>(
            () -> new int[1],
            (a, t) -> { a[0] += mapper.applyAsInt(t); },
            (a, b) -> { a[0] += b[0]; return a; },
            a -> a[0], CH_NOID);
}
 
Example 13
Source File: Collectors.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the arithmetic mean of an integer-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Double>
averagingInt(ToIntFunction<? super T> mapper) {
    return new CollectorImpl<>(
            () -> new long[2],
            (a, t) -> { a[0] += mapper.applyAsInt(t); a[1]++; },
            (a, b) -> { a[0] += b[0]; a[1] += b[1]; return a; },
            a -> (a[1] == 0) ? 0.0d : (double) a[0] / a[1], CH_NOID);
}
 
Example 14
Source File: Collectors.java    From jdk1.8-source-analysis with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the sum of a integer-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Integer>
summingInt(ToIntFunction<? super T> mapper) {
    return new CollectorImpl<>(
            () -> new int[1],
            (a, t) -> { a[0] += mapper.applyAsInt(t); },
            (a, b) -> { a[0] += b[0]; return a; },
            a -> a[0], CH_NOID);
}
 
Example 15
Source File: Collectors.java    From jdk8u60 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the sum of a integer-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Integer>
summingInt(ToIntFunction<? super T> mapper) {
    return new CollectorImpl<>(
            () -> new int[1],
            (a, t) -> { a[0] += mapper.applyAsInt(t); },
            (a, b) -> { a[0] += b[0]; return a; },
            a -> a[0], CH_NOID);
}
 
Example 16
Source File: Collectors.java    From jdk8u60 with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the arithmetic mean of an integer-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Double>
averagingInt(ToIntFunction<? super T> mapper) {
    return new CollectorImpl<>(
            () -> new long[2],
            (a, t) -> { a[0] += mapper.applyAsInt(t); a[1]++; },
            (a, b) -> { a[0] += b[0]; a[1] += b[1]; return a; },
            a -> (a[1] == 0) ? 0.0d : (double) a[0] / a[1], CH_NOID);
}
 
Example 17
Source File: Collectors.java    From JDKSourceCode1.8 with MIT License 3 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the sum of a integer-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Integer>
summingInt(ToIntFunction<? super T> mapper) {
    return new CollectorImpl<>(
            () -> new int[1],
            (a, t) -> { a[0] += mapper.applyAsInt(t); },
            (a, b) -> { a[0] += b[0]; return a; },
            a -> a[0], CH_NOID);
}
 
Example 18
Source File: Collectors.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the arithmetic mean of an integer-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Double>
averagingInt(ToIntFunction<? super T> mapper) {
    return new CollectorImpl<>(
            () -> new long[2],
            (a, t) -> { a[0] += mapper.applyAsInt(t); a[1]++; },
            (a, b) -> { a[0] += b[0]; a[1] += b[1]; return a; },
            a -> (a[1] == 0) ? 0.0d : (double) a[0] / a[1], CH_NOID);
}
 
Example 19
Source File: Collectors.java    From Bytecoder with Apache License 2.0 3 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the arithmetic mean of an integer-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be averaged
 * @return a {@code Collector} that produces the arithmetic mean of a
 * derived property
 */
public static <T> Collector<T, ?, Double>
averagingInt(ToIntFunction<? super T> mapper) {
    return new CollectorImpl<>(
            () -> new long[2],
            (a, t) -> { a[0] += mapper.applyAsInt(t); a[1]++; },
            (a, b) -> { a[0] += b[0]; a[1] += b[1]; return a; },
            a -> (a[1] == 0) ? 0.0d : (double) a[0] / a[1], CH_NOID);
}
 
Example 20
Source File: Collectors.java    From openjdk-jdk8u with GNU General Public License v2.0 3 votes vote down vote up
/**
 * Returns a {@code Collector} that produces the sum of a integer-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * @param <T> the type of the input elements
 * @param mapper a function extracting the property to be summed
 * @return a {@code Collector} that produces the sum of a derived property
 */
public static <T> Collector<T, ?, Integer>
summingInt(ToIntFunction<? super T> mapper) {
    return new CollectorImpl<>(
            () -> new int[1],
            (a, t) -> { a[0] += mapper.applyAsInt(t); },
            (a, b) -> { a[0] += b[0]; return a; },
            a -> a[0], CH_NOID);
}