类java.util.function.ToDoubleFunction源码实例Demo

下面列出了怎么用java.util.function.ToDoubleFunction的API类实例代码及写法,或者点击链接到github查看源代码。

@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
源代码2 项目: dragonwell8_jdk   文件: ReferencePipeline.java
@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
源代码3 项目: openjdk-jdk8u-backup   文件: ReferencePipeline.java
@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
源代码4 项目: jdk8u60   文件: Collectors.java
/**
 * Returns a {@code Collector} that produces the sum of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The sum returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * sum will be {@code NaN}.
 *
 * @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>
summingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the simple sum used to compute
     * the proper result if the stream contains infinite values of
     * the same sign.
     */
    return new CollectorImpl<>(
            () -> new double[3],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t));
                        a[2] += mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]);
                        a[2] += b[2];
                        return sumWithCompensation(a, b[1]); },
            a -> computeFinalSum(a),
            CH_NOID);
}
 
源代码5 项目: jdk8u-jdk   文件: ReferencePipeline.java
@Override
public final DoubleStream mapToDouble(ToDoubleFunction<? super P_OUT> mapper) {
    Objects.requireNonNull(mapper);
    return new DoublePipeline.StatelessOp<P_OUT>(this, StreamShape.REFERENCE,
                                    StreamOpFlag.NOT_SORTED | StreamOpFlag.NOT_DISTINCT) {
        @Override
        Sink<P_OUT> opWrapSink(int flags, Sink<Double> sink) {
            return new Sink.ChainedReference<P_OUT, Double>(sink) {
                @Override
                public void accept(P_OUT u) {
                    downstream.accept(mapper.applyAsDouble(u));
                }
            };
        }
    };
}
 
源代码6 项目: desugar_jdk_libs   文件: Collectors.java
/**
 * Returns a {@code Collector} that produces the sum of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The sum returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * sum will be {@code NaN}.
 *
 * @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>
summingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the simple sum used to compute
     * the proper result if the stream contains infinite values of
     * the same sign.
     */
    return new CollectorImpl<>(
            () -> new double[3],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t));
                        a[2] += mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]);
                        a[2] += b[2];
                        return sumWithCompensation(a, b[1]); },
            a -> computeFinalSum(a),
            CH_NOID);
}
 
源代码7 项目: micrometer   文件: DropwizardMeterRegistry.java
@Override
protected <T> io.micrometer.core.instrument.Gauge newGauge(Meter.Id id, @Nullable T obj, ToDoubleFunction<T> valueFunction) {
    final WeakReference<T> ref = new WeakReference<>(obj);
    Gauge<Double> gauge = () -> {
        T obj2 = ref.get();
        if (obj2 != null) {
            try {
                return valueFunction.applyAsDouble(obj2);
            } catch (Throwable ex) {
                logger.log("Failed to apply the value function for the gauge '" + id.getName() + "'.", ex);
            }
        }
        return nullGaugeValue();
    };
    registry.register(hierarchicalName(id), gauge);
    return new DropwizardGauge(id, gauge);
}
 
源代码8 项目: rheem   文件: OptimizationContext.java
/**
 * Update the {@link LoadProfile} and {@link TimeEstimate} of this instance.
 *
 * @param configuration provides the necessary functions
 */
private void updateCostEstimate(Configuration configuration) {
    if (!this.operator.isExecutionOperator()) return;

    // Estimate the LoadProfile.
    final LoadProfileEstimator loadProfileEstimator = this.getLoadProfileEstimator();
    try {
        this.loadProfile = LoadProfileEstimators.estimateLoadProfile(this, loadProfileEstimator);
    } catch (Exception e) {
        throw new RheemException(String.format("Load profile estimation for %s failed.", this.operator), e);
    }

    // Calculate the TimeEstimate.
    final ExecutionOperator executionOperator = (ExecutionOperator) this.operator;
    final Platform platform = executionOperator.getPlatform();
    final LoadProfileToTimeConverter timeConverter = configuration.getLoadProfileToTimeConverterProvider().provideFor(platform);
    this.timeEstimate = TimeEstimate.MINIMUM.plus(timeConverter.convert(this.loadProfile));
    if (OptimizationContext.this.logger.isDebugEnabled()) {
        OptimizationContext.this.logger.debug(
                "Setting time estimate of {} to {}.", this.operator, this.timeEstimate
        );
    }

    // Calculate the cost estimate.
    final TimeToCostConverter timeToCostConverter = configuration.getTimeToCostConverterProvider().provideFor(platform);
    this.costEstimate = timeToCostConverter.convertWithoutFixCosts(this.timeEstimate);

    // Squash the cost estimate.
    final ToDoubleFunction<ProbabilisticDoubleInterval> costSquasher = configuration.getCostSquasherProvider().provide();
    this.squashedCostEstimate = costSquasher.applyAsDouble(this.costEstimate);
}
 
源代码9 项目: micrometer   文件: StatsdGauge.java
StatsdGauge(Id id, StatsdLineBuilder lineBuilder, FluxSink<String> sink, @Nullable T obj, ToDoubleFunction<T> value, boolean alwaysPublish) {
    super(id);
    this.lineBuilder = lineBuilder;
    this.sink = sink;
    this.ref = new WeakReference<>(obj);
    this.value = value;
    this.alwaysPublish = alwaysPublish;
}
 
源代码10 项目: micrometer   文件: SimpleMeterRegistry.java
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
    switch (config.mode()) {
        case CUMULATIVE:
            return new CumulativeFunctionCounter<>(id, obj, countFunction);

        case STEP:
        default:
            return new StepFunctionCounter<>(id, clock, config.step().toMillis(), obj, countFunction);
    }
}
 
源代码11 项目: TencentKona-8   文件: BasicTest.java
public void testDoubleComparator() {
    Thing[] things = new Thing[doubleValues.length];
    for (int i=0; i<doubleValues.length; i++)
        things[i] = new Thing(0, 0L, doubleValues[i], null);
    Comparator<Thing> comp = Comparator.comparingDouble(new ToDoubleFunction<Thing>() {
        @Override
        public double applyAsDouble(Thing thing) {
            return thing.getDoubleField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
源代码12 项目: jdk8u60   文件: BasicTest.java
public void testDoubleComparator() {
    Thing[] things = new Thing[doubleValues.length];
    for (int i=0; i<doubleValues.length; i++)
        things[i] = new Thing(0, 0L, doubleValues[i], null);
    Comparator<Thing> comp = Comparator.comparingDouble(new ToDoubleFunction<Thing>() {
        @Override
        public double applyAsDouble(Thing thing) {
            return thing.getDoubleField();
        }
    });

    assertComparisons(things, comp, comparisons);
}
 
源代码13 项目: morpheus-core   文件: ArrayBase.java
@Override
public final Array<T> applyDoubles(ToDoubleFunction<ArrayValue<T>> function) {
    final int length = length();
    if (length > 0) {
        final ApplyValues action = new ApplyValues(0, length - 1, function);
        if (isParallel()) {
            ForkJoinPool.commonPool().invoke(action);
        } else {
            action.compute();
        }
    }
    return this;
}
 
源代码14 项目: morpheus-core   文件: Function1.java
/**
 * Creates an DOUBLE mapper that wraps to function provided
 * @param function  the function to wrap
 * @param <I>       the input type
 * @return          the newly created mapper
 */
public static <I,O> Function1<I,Double> toDouble(ToDoubleFunction<I> function) {
    return new Function1<I,Double>(FunctionStyle.DOUBLE) {
        @Override
        public final double applyAsDouble(I value) {
            return function.applyAsDouble(value);
        }
    };
}
 
源代码15 项目: micrometer   文件: DropwizardMeterRegistry.java
@Override
protected <T> FunctionTimer newFunctionTimer(Meter.Id id, T obj, ToLongFunction<T> countFunction, ToDoubleFunction<T> totalTimeFunction, TimeUnit totalTimeFunctionUnit) {
    DropwizardFunctionTimer<T> ft = new DropwizardFunctionTimer<>(id, clock, obj, countFunction, totalTimeFunction,
            totalTimeFunctionUnit, getBaseTimeUnit());
    registry.register(hierarchicalName(id), ft.getDropwizardMeter());
    return ft;
}
 
源代码16 项目: micrometer   文件: DropwizardFunctionCounter.java
DropwizardFunctionCounter(Id id, Clock clock,
                          T obj, ToDoubleFunction<T> f) {
    super(id);
    this.ref = new WeakReference<>(obj);
    this.f = f;
    this.rate = new DropwizardRate(clock);
    this.dropwizardMeter = new Meter(new DropwizardClock(clock)) {
        @Override
        public double getFifteenMinuteRate() {
            count();
            return rate.getFifteenMinuteRate();
        }

        @Override
        public double getFiveMinuteRate() {
            count();
            return rate.getFiveMinuteRate();
        }

        @Override
        public double getOneMinuteRate() {
            count();
            return rate.getOneMinuteRate();
        }

        @Override
        public long getCount() {
            return (long) count();
        }
    };
}
 
源代码17 项目: micrometer   文件: StatsdFunctionTimer.java
StatsdFunctionTimer(Id id, T obj, ToLongFunction<T> countFunction, ToDoubleFunction<T> totalTimeFunction,
                    TimeUnit totalTimeFunctionUnit, TimeUnit baseTimeUnit,
                    StatsdLineBuilder lineBuilder, FluxSink<String> sink) {
    super(id, obj, countFunction, totalTimeFunction, totalTimeFunctionUnit, baseTimeUnit);
    this.lineBuilder = lineBuilder;
    this.sink = sink;
}
 
源代码18 项目: micrometer   文件: PrometheusMeterRegistry.java
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
    FunctionCounter fc = new CumulativeFunctionCounter<>(id, obj, countFunction);
    applyToCollector(id, (collector) -> {
        List<String> tagValues = tagValues(id);
        collector.add(tagValues, (conventionName, tagKeys) -> Stream.of(new MicrometerCollector.Family(Collector.Type.COUNTER, conventionName,
                new Collector.MetricFamilySamples.Sample(conventionName, tagKeys, tagValues, fc.count())
        )));
    });
    return fc;
}
 
源代码19 项目: jdk8u-jdk   文件: Collectors.java
/**
 * Returns a {@code Collector} that produces the arithmetic mean of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The average returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * average will be {@code NaN}.
 *
 * @implNote The {@code double} format can represent all
 * consecutive integers in the range -2<sup>53</sup> to
 * 2<sup>53</sup>. If the pipeline has more than 2<sup>53</sup>
 * values, the divisor in the average computation will saturate at
 * 2<sup>53</sup>, leading to additional numerical errors.
 *
 * @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>
averagingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the number of values seen.
     */
    return new CollectorImpl<>(
            () -> new double[4],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t)); a[2]++; a[3]+= mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]); sumWithCompensation(a, b[1]); a[2] += b[2]; a[3] += b[3]; return a; },
            a -> (a[2] == 0) ? 0.0d : (computeFinalSum(a) / a[2]),
            CH_NOID);
}
 
源代码20 项目: jdk1.8-source-analysis   文件: Collectors.java
/**
 * Returns a {@code Collector} that produces the arithmetic mean of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The average returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * average will be {@code NaN}.
 *
 * @implNote The {@code double} format can represent all
 * consecutive integers in the range -2<sup>53</sup> to
 * 2<sup>53</sup>. If the pipeline has more than 2<sup>53</sup>
 * values, the divisor in the average computation will saturate at
 * 2<sup>53</sup>, leading to additional numerical errors.
 *
 * @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>
averagingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the number of values seen.
     */
    return new CollectorImpl<>(
            () -> new double[4],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t)); a[2]++; a[3]+= mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]); sumWithCompensation(a, b[1]); a[2] += b[2]; a[3] += b[3]; return a; },
            a -> (a[2] == 0) ? 0.0d : (computeFinalSum(a) / a[2]),
            CH_NOID);
}
 
源代码21 项目: micrometer   文件: OpenTSDBMeterRegistry.java
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
    return new CumulativeFunctionCounter<>(id, obj, countFunction);
}
 
源代码22 项目: Wurst7   文件: ClickAuraHack.java
private Priority(String name,
	ToDoubleFunction<LivingEntity> keyExtractor)
{
	this.name = name;
	comparator = Comparator.comparingDouble(keyExtractor);
}
 
源代码23 项目: openjdk-jdk9   文件: DefaultMethodStreams.java
@Override
public DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) {
    return s.mapToDouble(mapper);
}
 
源代码24 项目: Wurst7   文件: KillauraHack.java
private Priority(String name,
	ToDoubleFunction<LivingEntity> keyExtractor)
{
	this.name = name;
	comparator = Comparator.comparingDouble(keyExtractor);
}
 
源代码25 项目: micrometer   文件: StrongReferenceGaugeFunction.java
StrongReferenceGaugeFunction(@Nullable T obj, ToDoubleFunction<T> f) {
    this.obj = obj;
    this.f = f;
}
 
源代码26 项目: dragonwell8_jdk   文件: Collectors.java
/**
 * Returns a {@code Collector} that produces the arithmetic mean of a double-valued
 * function applied to the input elements.  If no elements are present,
 * the result is 0.
 *
 * <p>The average returned can vary depending upon the order in which
 * values are recorded, due to accumulated rounding error in
 * addition of values of differing magnitudes. Values sorted by increasing
 * absolute magnitude tend to yield more accurate results.  If any recorded
 * value is a {@code NaN} or the sum is at any point a {@code NaN} then the
 * average will be {@code NaN}.
 *
 * @implNote The {@code double} format can represent all
 * consecutive integers in the range -2<sup>53</sup> to
 * 2<sup>53</sup>. If the pipeline has more than 2<sup>53</sup>
 * values, the divisor in the average computation will saturate at
 * 2<sup>53</sup>, leading to additional numerical errors.
 *
 * @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>
averagingDouble(ToDoubleFunction<? super T> mapper) {
    /*
     * In the arrays allocated for the collect operation, index 0
     * holds the high-order bits of the running sum, index 1 holds
     * the low-order bits of the sum computed via compensated
     * summation, and index 2 holds the number of values seen.
     */
    return new CollectorImpl<>(
            () -> new double[4],
            (a, t) -> { sumWithCompensation(a, mapper.applyAsDouble(t)); a[2]++; a[3]+= mapper.applyAsDouble(t);},
            (a, b) -> { sumWithCompensation(a, b[0]); sumWithCompensation(a, b[1]); a[2] += b[2]; a[3] += b[3]; return a; },
            a -> (a[2] == 0) ? 0.0d : (computeFinalSum(a) / a[2]),
            CH_NOID);
}
 
源代码27 项目: micrometer   文件: CompositeMeterRegistry.java
@Override
protected <T> Gauge newGauge(Meter.Id id, @Nullable T obj, ToDoubleFunction<T> valueFunction) {
    return new CompositeGauge<>(id, obj, valueFunction);
}
 
源代码28 项目: micrometer   文件: MultiGauge.java
private Row(Tags uniqueTags, T obj, ToDoubleFunction<T> valueFunction) {
    this.uniqueTags = uniqueTags;
    this.obj = obj;
    this.valueFunction = valueFunction;
}
 
源代码29 项目: micrometer   文件: CompositeMeterRegistry.java
@Override
protected <T> TimeGauge newTimeGauge(Meter.Id id, @Nullable T obj, TimeUnit valueFunctionUnit, ToDoubleFunction<T> valueFunction) {
    return new CompositeTimeGauge<>(id, obj, valueFunctionUnit, valueFunction);
}
 
源代码30 项目: freecol   文件: REFAIPlayer.java
/**
 * Find suitable colony targets.
 *
 * @param aiu The {@code AIUnit} to search with.
 * @param port If true, insist on the colonies being ports.
 * @param aiCarrier The {@code AIUnit} to use as a carrier.
 * @return A list of {@code TargetTuple} target choices.
 */
private List<TargetTuple> findColonyTargets(AIUnit aiu, boolean port,
                                            AIUnit aiCarrier) {
    final Player player = getPlayer();
    final Unit unit = aiu.getUnit();
    final Unit carrier = aiCarrier.getUnit();
    final CachingFunction<Colony, PathNode> pathMapper
        = new CachingFunction<Colony, PathNode>(c ->
            unit.findPath(carrier, c, carrier));
    final Predicate<Colony> pathPred = c ->
        pathMapper.apply(c) != null;
    final Function<Colony, TargetTuple> newTupleMapper = c -> {
        PathNode path = pathMapper.apply(c);
        return new TargetTuple(c, path,
            UnitSeekAndDestroyMission.scorePath(aiu, path));
    };
    final List<TargetTuple> targets
        = transform(flatten(player.getRebels(),
                ((port) ? Player::getConnectedPorts :Player::getColonies)),
            pathPred, newTupleMapper);
    if (targets.isEmpty()) return targets; // Should not happen

    // Increase score for drydock/s, musket and tools suppliers,
    // but decrease for fortifications.
    // FIXME: use Modifiers?
    final int percentTwiddle = 20; // Perturb score by +/-20%
    int[] twiddle = randomInts(logger, "REF target twiddle",
                               getAIRandom(), 2*percentTwiddle+1,
                               targets.size());
    int twidx = 0;
    for (TargetTuple t : targets) {
        final ToDoubleFunction<Building> bdf = b ->
            ((b.hasAbility(Ability.REPAIR_UNITS)) ? 1.5 : 1.0)
            * product(b.getOutputs(), ag ->
                (ag.getType().getMilitary()) ? 2.0
                : (ag.getType().isBuildingMaterial()
                    && ag.getType().isRefined()) ? 1.5
                : 1.0);
        t.score *= 0.01 * (101 - Math.min(100, t.colony.getSoL()))
            * product(t.colony.getBuildings(), b -> b.getLevel() > 1, bdf)
            * ((6 - ((!t.colony.hasStockade()) ? 0
                        : t.colony.getStockade().getLevel())) / 6.0)
            * (1.0 + 0.01 * (twiddle[twidx++] - percentTwiddle));
    }
    targets.sort(Comparator.naturalOrder());
    return targets;
}
 
 类所在包
 类方法
 同包方法