Java Code Examples for java.util.OptionalDouble#of()

The following examples show how to use java.util.OptionalDouble#of() . 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: DoublePipeline.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
/**
 * {@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();
}
 
Example 2
Source File: DoublePipeline.java    From Java8CN with Apache License 2.0 6 votes vote down vote up
/**
 * {@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();
}
 
Example 3
Source File: DoubleStreamEx.java    From streamex with Apache License 2.0 6 votes vote down vote up
/**
 * 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);
}
 
Example 4
Source File: BasicDouble.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@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));
}
 
Example 5
Source File: Numbers.java    From helper with MIT License 5 votes vote down vote up
@Nonnull
public static OptionalDouble parseFloat(@Nonnull String s) {
    try {
        return OptionalDouble.of(Float.parseFloat(s));
    } catch (NumberFormatException e) {
        return OptionalDouble.empty();
    }
}
 
Example 6
Source File: MobileDeviceAttributesTransformer.java    From arcusplatform with Apache License 2.0 5 votes vote down vote up
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();
}
 
Example 7
Source File: OptionalDoubleThriftCodec.java    From drift with Apache License 2.0 5 votes vote down vote up
@Override
public OptionalDouble read(TProtocolReader protocol)
        throws Exception
{
    requireNonNull(protocol, "protocol is null");
    return OptionalDouble.of(protocol.readDouble());
}
 
Example 8
Source File: IntPipeline.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@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();
}
 
Example 9
Source File: IntPipeline.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@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();
}
 
Example 10
Source File: BasicDouble.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@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));
}
 
Example 11
Source File: LongPipeline.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@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();
}
 
Example 12
Source File: LongPipeline.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@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();
}
 
Example 13
Source File: Metrics.java    From presto with Apache License 2.0 5 votes vote down vote up
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 + "\")";
        }
    };
}
 
Example 14
Source File: IntPipeline.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
@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();
}
 
Example 15
Source File: ReduceOps.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
/**
 * 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();
        }
    };
}
 
Example 16
Source File: FindOps.java    From openjdk-8-source with GNU General Public License v2.0 4 votes vote down vote up
@Override
public OptionalDouble get() {
    return hasValue ? OptionalDouble.of(value) : null;
}
 
Example 17
Source File: OptionalUtils.java    From dalesbred with MIT License 4 votes vote down vote up
public static @NotNull OptionalDouble optionalDoubleOfNullable(@Nullable Double v) {
    return v != null ? OptionalDouble.of(v) : OptionalDouble.empty();
}
 
Example 18
Source File: OptionalDoubleExample.java    From levelup-java-examples with Apache License 2.0 3 votes vote down vote up
@Test
public void optional_double_of() {

	OptionalDouble optionalDouble = OptionalDouble.of(89);
	
	assertEquals(89, optionalDouble.getAsDouble(), 0);
}
 
Example 19
Source File: IborCapletFloorletPeriod.java    From Strata with Apache License 2.0 2 votes vote down vote up
/**
 * 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();
}
 
Example 20
Source File: IborRateCalculation.java    From Strata with Apache License 2.0 2 votes vote down vote up
/**
 * 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();
}