下面列出了怎么用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));
}
};
}
};
}
@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));
}
};
}
};
}
@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));
}
};
}
};
}
/**
* 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);
}
@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));
}
};
}
};
}
/**
* 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);
}
@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);
}
/**
* 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);
}
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;
}
@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);
}
}
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);
}
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);
}
@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;
}
/**
* 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);
}
};
}
@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;
}
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();
}
};
}
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;
}
@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;
}
/**
* 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);
}
/**
* 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);
}
@Override
protected <T> FunctionCounter newFunctionCounter(Meter.Id id, T obj, ToDoubleFunction<T> countFunction) {
return new CumulativeFunctionCounter<>(id, obj, countFunction);
}
private Priority(String name,
ToDoubleFunction<LivingEntity> keyExtractor)
{
this.name = name;
comparator = Comparator.comparingDouble(keyExtractor);
}
@Override
public DoubleStream mapToDouble(ToDoubleFunction<? super T> mapper) {
return s.mapToDouble(mapper);
}
private Priority(String name,
ToDoubleFunction<LivingEntity> keyExtractor)
{
this.name = name;
comparator = Comparator.comparingDouble(keyExtractor);
}
StrongReferenceGaugeFunction(@Nullable T obj, ToDoubleFunction<T> f) {
this.obj = obj;
this.f = f;
}
/**
* 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);
}
@Override
protected <T> Gauge newGauge(Meter.Id id, @Nullable T obj, ToDoubleFunction<T> valueFunction) {
return new CompositeGauge<>(id, obj, valueFunction);
}
private Row(Tags uniqueTags, T obj, ToDoubleFunction<T> valueFunction) {
this.uniqueTags = uniqueTags;
this.obj = obj;
this.valueFunction = valueFunction;
}
@Override
protected <T> TimeGauge newTimeGauge(Meter.Id id, @Nullable T obj, TimeUnit valueFunctionUnit, ToDoubleFunction<T> valueFunction) {
return new CompositeTimeGauge<>(id, obj, valueFunctionUnit, valueFunction);
}
/**
* 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;
}