下面列出了java.util.OptionalDouble#of ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
/**
* {@inheritDoc}
*
* @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.
*/
@Override
public final OptionalDouble average() {
/*
* 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, index 2 holds the number of values seen, index 3
* holds the simple sum.
*/
double[] avg = collect(() -> new double[4],
(ll, d) -> {
ll[2]++;
Collectors.sumWithCompensation(ll, d);
ll[3] += d;
},
(ll, rr) -> {
Collectors.sumWithCompensation(ll, rr[0]);
Collectors.sumWithCompensation(ll, rr[1]);
ll[2] += rr[2];
ll[3] += rr[3];
});
return avg[2] > 0
? OptionalDouble.of(Collectors.computeFinalSum(avg) / avg[2])
: OptionalDouble.empty();
}
/**
* Returns the minimum element of this stream according to the provided key
* extractor function.
*
* <p>
* This is a terminal operation.
*
* @param <V> the type of the {@code Comparable} sort key
* @param keyExtractor a non-interfering, stateless function
* @return an {@code OptionalDouble} describing the first element of this
* stream for which the lowest value was returned by key extractor,
* or an empty {@code OptionalDouble} if the stream is empty
* @since 0.1.2
*/
public <V extends Comparable<? super V>> OptionalDouble minBy(DoubleFunction<V> keyExtractor) {
ObjDoubleBox<V> result = collect(() -> new ObjDoubleBox<>(null, 0), (box, i) -> {
V val = Objects.requireNonNull(keyExtractor.apply(i));
if (box.a == null || box.a.compareTo(val) > 0) {
box.a = val;
box.b = i;
}
}, (box1, box2) -> {
if (box2.a != null && (box1.a == null || box1.a.compareTo(box2.a) > 0)) {
box1.a = box2.a;
box1.b = box2.b;
}
});
return result.a == null ? OptionalDouble.empty() : OptionalDouble.of(result.b);
}
/**
* {@inheritDoc}
*
* @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.
*/
@Override
public final OptionalDouble average() {
/*
* 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, index 2 holds the number of values seen, index 3
* holds the simple sum.
*/
double[] avg = collect(() -> new double[4],
(ll, d) -> {
ll[2]++;
Collectors.sumWithCompensation(ll, d);
ll[3] += d;
},
(ll, rr) -> {
Collectors.sumWithCompensation(ll, rr[0]);
Collectors.sumWithCompensation(ll, rr[1]);
ll[2] += rr[2];
ll[3] += rr[3];
});
return avg[2] > 0
? OptionalDouble.of(Collectors.computeFinalSum(avg) / avg[2])
: OptionalDouble.empty();
}
@Override
public final OptionalDouble average() {
long[] avg = collect(() -> new long[2],
(ll, i) -> {
ll[0]++;
ll[1] += i;
},
(ll, rr) -> {
ll[0] += rr[0];
ll[1] += rr[1];
});
return avg[0] > 0
? OptionalDouble.of((double) avg[1] / avg[0])
: OptionalDouble.empty();
}
@Test(groups = "unit")
public void testEmpty() {
OptionalDouble empty = OptionalDouble.empty();
OptionalDouble present = OptionalDouble.of(1.0);
// empty
assertTrue(empty.equals(empty));
assertTrue(empty.equals(OptionalDouble.empty()));
assertTrue(!empty.equals(present));
assertTrue(0 == empty.hashCode());
assertTrue(!empty.toString().isEmpty());
assertTrue(!empty.isPresent());
empty.ifPresent(v -> { fail(); });
AtomicBoolean emptyCheck = new AtomicBoolean();
empty.ifPresentOrElse(v -> fail(), () -> emptyCheck.set(true));
assertTrue(emptyCheck.get());
try {
empty.ifPresentOrElse(v -> fail(), () -> { throw new ObscureException(); });
fail();
} catch (ObscureException expected) {
} catch (AssertionError e) {
throw e;
} catch (Throwable t) {
fail();
}
assertEquals(2.0, empty.orElse(2.0));
assertEquals(2.0, empty.orElseGet(()-> 2.0));
}
public static Metric nullsFraction(String columnName)
{
return new Metric()
{
@Override
public OptionalDouble getValueFromPlanNodeEstimate(PlanNodeStatsEstimate planNodeStatsEstimate, StatsContext statsContext)
{
return asOptional(getSymbolStatistics(planNodeStatsEstimate, columnName, statsContext).getNullsFraction());
}
@Override
public OptionalDouble getValueFromAggregationQueryResult(Object value)
{
return OptionalDouble.of(((Number) value).doubleValue());
}
@Override
public String getComputingAggregationSql()
{
return "(count(*) filter(where " + columnName + " is null)) / cast(count(*) as double)";
}
@Override
public String toString()
{
return "nullsFraction(\"" + columnName + "\")";
}
};
}
@Override
public final OptionalDouble average() {
long[] avg = collect(() -> new long[2],
(ll, i) -> {
ll[0]++;
ll[1] += i;
},
(ll, rr) -> {
ll[0] += rr[0];
ll[1] += rr[1];
});
return avg[0] > 0
? OptionalDouble.of((double) avg[1] / avg[0])
: OptionalDouble.empty();
}
@Override
public final OptionalDouble average() {
long[] avg = collect(() -> new long[2],
(ll, i) -> {
ll[0]++;
ll[1] += i;
},
(ll, rr) -> {
ll[0] += rr[0];
ll[1] += rr[1];
});
return avg[0] > 0
? OptionalDouble.of((double) avg[1] / avg[0])
: OptionalDouble.empty();
}
@Test(groups = "unit")
public void testPresent() {
OptionalDouble empty = OptionalDouble.empty();
OptionalDouble present = OptionalDouble.of(1.0);
// present
assertTrue(present.equals(present));
assertFalse(present.equals(OptionalDouble.of(0.0)));
assertTrue(present.equals(OptionalDouble.of(1.0)));
assertTrue(!present.equals(empty));
assertTrue(Double.hashCode(1.0) == present.hashCode());
assertFalse(present.toString().isEmpty());
assertTrue(-1 != present.toString().indexOf(Double.toString(present.getAsDouble()).toString()));
assertEquals(1.0, present.getAsDouble());
try {
present.ifPresent(v -> { throw new ObscureException(); });
fail();
} catch(ObscureException expected) {
}
assertEquals(1.0, present.orElse(2.0));
assertEquals(1.0, present.orElseGet(null));
assertEquals(1.0, present.orElseGet(()-> 2.0));
assertEquals(1.0, present.orElseGet(()-> 3.0));
assertEquals(1.0, present.<RuntimeException>orElseThrow(null));
assertEquals(1.0, present.<RuntimeException>orElseThrow(ObscureException::new));
}
@Override
public final OptionalDouble average() {
long[] avg = collect(() -> new long[2],
(ll, i) -> {
ll[0]++;
ll[1] += i;
},
(ll, rr) -> {
ll[0] += rr[0];
ll[1] += rr[1];
});
return avg[0] > 0
? OptionalDouble.of((double) avg[1] / avg[0])
: OptionalDouble.empty();
}
@Override
public final OptionalDouble average() {
long[] avg = collect(() -> new long[2],
(ll, i) -> {
ll[0]++;
ll[1] += i;
},
(ll, rr) -> {
ll[0] += rr[0];
ll[1] += rr[1];
});
return avg[0] > 0
? OptionalDouble.of((double) avg[1] / avg[0])
: OptionalDouble.empty();
}
@Override
public OptionalDouble read(TProtocolReader protocol)
throws Exception
{
requireNonNull(protocol, "protocol is null");
return OptionalDouble.of(protocol.readDouble());
}
private static OptionalDouble getDiagonalLength(OptionalDouble dim1, OptionalDouble dim2) {
if (dim1.isPresent() && dim2.isPresent()){
return OptionalDouble.of((Math.sqrt(Math.pow(dim1.getAsDouble(), 2) + Math.pow(dim2.getAsDouble(), 2))));
}
return OptionalDouble.empty();
}
@Nonnull
public static OptionalDouble parseFloat(@Nonnull String s) {
try {
return OptionalDouble.of(Float.parseFloat(s));
} catch (NumberFormatException e) {
return OptionalDouble.empty();
}
}
@Override
public OptionalDouble get() {
return hasValue ? OptionalDouble.of(value) : null;
}
/**
* Constructs a {@code TerminalOp} that implements a functional reduce on
* {@code double} values, producing an optional double result.
*
* @param operator the combining function
* @return a {@code TerminalOp} implementing the reduction
*/
public static TerminalOp<Double, OptionalDouble>
makeDouble(DoubleBinaryOperator operator) {
Objects.requireNonNull(operator);
class ReducingSink
implements AccumulatingSink<Double, OptionalDouble, ReducingSink>, Sink.OfDouble {
private boolean empty;
private double state;
public void begin(long size) {
empty = true;
state = 0;
}
@Override
public void accept(double t) {
if (empty) {
empty = false;
state = t;
}
else {
state = operator.applyAsDouble(state, t);
}
}
@Override
public OptionalDouble get() {
return empty ? OptionalDouble.empty() : OptionalDouble.of(state);
}
@Override
public void combine(ReducingSink other) {
if (!other.empty)
accept(other.state);
}
}
return new ReduceOp<Double, OptionalDouble, ReducingSink>(StreamShape.DOUBLE_VALUE) {
@Override
public ReducingSink makeSink() {
return new ReducingSink();
}
};
}
public static @NotNull OptionalDouble optionalDoubleOfNullable(@Nullable Double v) {
return v != null ? OptionalDouble.of(v) : OptionalDouble.empty();
}
@Test
public void optional_double_of() {
OptionalDouble optionalDouble = OptionalDouble.of(89);
assertEquals(89, optionalDouble.getAsDouble(), 0);
}
/**
* Gets the optional floorlet strike.
* <p>
* This defines the strike value of a floorlet.
* <p>
* If the period is not a floorlet, this field will be absent.
* @return the optional value of the property, not null
*/
public OptionalDouble getFloorlet() {
return floorlet != null ? OptionalDouble.of(floorlet) : OptionalDouble.empty();
}
/**
* Gets the rate of the first regular reset period, optional.
* A 5% rate will be expressed as 0.05.
* <p>
* In certain circumstances two counterparties agree the rate of the first fixing
* when the contract starts, and it is used in place of one observed fixing.
* For all other fixings, the rate is observed via the normal fixing process.
* <p>
* This property allows the rate of the first reset period of the first <i>regular</i> accrual period
* to be controlled. Note that if there is an initial stub, this will be the second reset period.
* Other calculation elements, such as gearing or spread, still apply to the rate specified here.
* <p>
* If the first rate applies to the initial stub rather than the regular accrual periods
* it must be specified using {@code initialStub}. Alternatively, {@code firstRate} can be used.
* <p>
* This property follows the definition in FpML. See also {@code firstRate}.
* @return the optional value of the property, not null
*/
public OptionalDouble getFirstRegularRate() {
return firstRegularRate != null ? OptionalDouble.of(firstRegularRate) : OptionalDouble.empty();
}