Java 类java.util.OptionalDouble 实例源码
项目:GitHub
文件:JdkOptionalTest.java
@Test
public void equals() {
ImmutableJdkOptionals o1 = ImmutableJdkOptionals.of()
.withV2("v2")
.withI1(1)
.withD1(1.0);
ImmutableJdkOptionals o2 = ImmutableJdkOptionals.of(
Optional.of("v2"),
OptionalInt.of(1),
OptionalLong.empty(),
OptionalDouble.of(1.0));
check(o1).is(o2);
check(o1.hashCode()).is(o2.hashCode());
}
项目:Java-Data-Science-Made-Easy
文件:Main.java
public void usingJava8() {
// Using Java 8 techniques to find mean
OptionalDouble mean = Arrays.stream(testData).average();
if (mean.isPresent()) {
out.println("The mean is " + mean.getAsDouble());
} else {
out.println("The stream was empty");
}
mean = Arrays.stream(testData).average();
mean.ifPresent(x -> out.println("The mean is " + x));
mean = Arrays.stream(testData).average();
out.println("The mean is " + mean.orElse(0));
}
项目:morpheus-core
文件:MinMaxTests.java
@Test(dataProvider = "parallel")
public void testMaxColumn(boolean parallel) {
final DataFrame<String,String> frame = TestDataFrames.random(Double.class, 100000, 10).applyDoubles(v -> Math.random() * 10d);
final DataFrameColumns<String,String> columns = parallel ? frame.cols().parallel() : frame.cols();
final Optional<DataFrameColumn<String,String>> colMatch = columns.max((col1, col2) -> {
final double diff1 = col1.getDouble("R5") - col1.getDouble("R8");
final double diff2 = col2.getDouble("R5") - col2.getDouble("R8");
return Double.compare(Math.abs(diff1), Math.abs(diff2));
});
assertTrue(colMatch.isPresent(), "Column was matched");
final DataFrameColumn<String,String> column = colMatch.get();
final OptionalDouble expectedMin = frame.cols().stream().mapToDouble(col -> Math.abs(col.getDouble("R5") - col.getDouble("R8"))).max();
final double actualMin = Math.abs(column.getDouble("R5") - column.getDouble("R8"));
assertTrue(expectedMin.isPresent());
System.out.println("Min diff for " + column.key() + " for row " + column.ordinal());
assertEquals(actualMin, expectedMin.getAsDouble(), 0.0001);
}
项目:chordatlas
文件:Regularizer.java
private double[] alignMFs( List<MiniFacade> out, boolean onlyOneHard ) {
OptionalDouble left = out.stream().filter( m -> !m.softLeft && (onlyOneHard || !m.softRight)).mapToDouble( m -> m.left ).average();
if ( left.isPresent() )
lp = left.getAsDouble();
else if (!onlyOneHard)
return null;
else
lp = out.stream().mapToDouble( m -> m.left ).min().getAsDouble();
OptionalDouble right = out.stream().filter( m -> !m.softRight && (onlyOneHard || !m.softLeft) ).mapToDouble( m -> m.left + m.width ).average();
if ( right.isPresent() )
rp = right.getAsDouble();
else if (!onlyOneHard)
return null;
else
rp = out.stream().mapToDouble( m -> m.left + m.width ).max().getAsDouble();
return new double[] {lp, rp};
}
项目:morpheus-core
文件:MinMaxTests.java
@Test(dataProvider = "parallel")
public void testMaxRow(boolean parallel) {
final DataFrame<String,String> frame = TestDataFrames.random(Double.class, 100000, 10).applyDoubles(v -> Math.random() * 10d);
final DataFrameRows<String,String> rows = parallel ? frame.rows().parallel() : frame.rows();
final Optional<DataFrameRow<String,String>> rowMatch = rows.max((row1, row2) -> {
final double diff1 = row1.getDouble("C5") - row1.getDouble("C8");
final double diff2 = row2.getDouble("C5") - row2.getDouble("C8");
return Double.compare(Math.abs(diff1), Math.abs(diff2));
});
assertTrue(rowMatch.isPresent(), "Row was matched");
final DataFrameRow<String,String> minRow = rowMatch.get();
final OptionalDouble expectedMin = frame.rows().stream().mapToDouble(row -> Math.abs(row.getDouble("C5") - row.getDouble("C8"))).max();
final double actualMin = Math.abs(minRow.getDouble("C5") - minRow.getDouble("C8"));
assertTrue(expectedMin.isPresent());
System.out.println("Min diff for " + minRow.key() + " for row " + minRow.ordinal());
assertEquals(actualMin, expectedMin.getAsDouble(), 0.0001);
}
项目:OpenJSharp
文件:DoublePipeline.java
/**
* {@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();
}
项目:morpheus-core
文件:MinMaxTests.java
@Test(dataProvider = "parallel")
public void testMinRow(boolean parallel) {
final DataFrame<String,String> frame = TestDataFrames.random(Double.class, 100000, 10).applyDoubles(v -> Math.random() * 10d);
final DataFrameRows<String,String> rows = parallel ? frame.rows().parallel() : frame.rows();
final Optional<DataFrameRow<String,String>> rowMatch = rows.min((row1, row2) -> {
final double diff1 = row1.getDouble("C5") - row1.getDouble("C8");
final double diff2 = row2.getDouble("C5") - row2.getDouble("C8");
return Double.compare(Math.abs(diff1), Math.abs(diff2));
});
assertTrue(rowMatch.isPresent(), "Row was matched");
final DataFrameRow<String,String> minRow = rowMatch.get();
final OptionalDouble expectedMin = frame.rows().stream().mapToDouble(row -> Math.abs(row.getDouble("C5") - row.getDouble("C8"))).min();
final double actualMin = Math.abs(minRow.getDouble("C5") - minRow.getDouble("C8"));
assertTrue(expectedMin.isPresent());
System.out.println("Min diff for " + minRow.key() + " for row " + minRow.ordinal());
assertEquals(actualMin, expectedMin.getAsDouble(), 0.0001);
}
项目:java-velocypack-module-jdk8
文件:VPackOptionalTest.java
@Test
public void serializeOptionalPrimitive() {
final OptionalPrimitiveTestEntity entity = new OptionalPrimitiveTestEntity();
entity.d = OptionalDouble.of(69.5);
entity.i = OptionalInt.of(69);
entity.l = OptionalLong.of(69L);
final VPackSlice vpack = vp.serialize(entity);
assertThat(vpack, is(notNullValue()));
assertThat(vpack.isObject(), is(true));
assertThat(vpack.get("d").isDouble(), is(true));
assertThat(vpack.get("d").getAsDouble(), is(69.5));
assertThat(vpack.get("i").isInteger(), is(true));
assertThat(vpack.get("i").getAsInt(), is(69));
assertThat(vpack.get("l").isInteger(), is(true));
assertThat(vpack.get("l").getAsLong(), is(69L));
}
项目:uroborosql
文件:PropertyMapperTest.java
@Test
public void test02() throws Exception {
try (SqlAgent agent = config.agent()) {
agent.required(() -> {
PropertyMapperTestEntity test1 = new PropertyMapperTestEntity(1);
test1.intValue = OptionalInt.empty();
test1.longValue = OptionalLong.empty();
test1.doubleValue = OptionalDouble.empty();
test1.dateValue = null;
test1.datetimeValue = null;
test1.enumValue = null;
test1.bigIntValue = null;
agent.insert(test1);
PropertyMapperTestEntity data = agent.find(PropertyMapperTestEntity.class, 1).orElse(null);
assertThat(data, is(test1));
});
}
}
项目:jdk8u-jdk
文件:DoublePipeline.java
/**
* {@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();
}
项目:morpheus-core
文件:MinMaxTests.java
@Test(dataProvider = "parallel")
public void testMinColumn(boolean parallel) {
final DataFrame<String,String> frame = TestDataFrames.random(Double.class, 100000, 10).applyDoubles(v -> Math.random() * 10d);
final DataFrameColumns<String,String> columns = parallel ? frame.cols().parallel() : frame.cols();
final Optional<DataFrameColumn<String,String>> colMatch = columns.min((col1, col2) -> {
final double diff1 = col1.getDouble("R5") - col1.getDouble("R8");
final double diff2 = col2.getDouble("R5") - col2.getDouble("R8");
return Double.compare(Math.abs(diff1), Math.abs(diff2));
});
assertTrue(colMatch.isPresent(), "Column was matched");
final DataFrameColumn<String,String> column = colMatch.get();
final OptionalDouble expectedMin = frame.cols().stream().mapToDouble(col -> Math.abs(col.getDouble("R5") - col.getDouble("R8"))).min();
final double actualMin = Math.abs(column.getDouble("R5") - column.getDouble("R8"));
assertTrue(expectedMin.isPresent());
System.out.println("Min diff for " + column.key() + " for row " + column.ordinal());
assertEquals(actualMin, expectedMin.getAsDouble(), 0.0001);
}
项目:openjdk-jdk10
文件:DoublePipeline.java
/**
* {@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();
}
项目:googles-monorepo-demo
文件:StreamsTest.java
public void testFindLast_doubleStream() {
Truth.assertThat(findLast(DoubleStream.of())).isEqualTo(OptionalDouble.empty());
Truth.assertThat(findLast(DoubleStream.of(1, 2, 3, 4, 5))).isEqualTo(OptionalDouble.of(5));
// test with a large, not-subsized Spliterator
List<Long> list =
LongStream.rangeClosed(0, 10000).boxed().collect(Collectors.toCollection(LinkedList::new));
Truth.assertThat(findLast(list.stream().mapToDouble(i -> i)))
.isEqualTo(OptionalDouble.of(10000));
// no way to find out the stream is empty without walking its spliterator
Truth.assertThat(findLast(list.stream().mapToDouble(i -> i).filter(i -> i < 0)))
.isEqualTo(OptionalDouble.empty());
}
项目:GestureFX
文件:LenaSample.java
private static OptionalDouble parseDouble(String text) {
try {
return OptionalDouble.of(Double.parseDouble(text));
} catch (NumberFormatException e) {
return OptionalDouble.empty();
}
}
项目:test-as-you-think
文件:ResultOfEventTest.java
@Test
public void should_verify_an_actual_optional_double_is_conform_to_an_expected_result() {
assertThat(resultOf(() -> {
gwtMock.whenAnEventHappensInRelationToAnActionOfTheConsumer();
return OptionalDouble.of(123);
}).isPresent()).hasSameClassAs(assertThat(OptionalDouble.empty()));
}
项目:Machine-Learning-End-to-Endguide-for-Java-developers
文件:Main.java
public void usingJava8() {
// Using Java 8 techniques to find mean
OptionalDouble mean = Arrays.stream(testData).average();
if (mean.isPresent()) {
out.println("The mean is " + mean.getAsDouble());
} else {
out.println("The stream was empty");
}
mean = Arrays.stream(testData).average();
mean.ifPresent(x -> out.println("The mean is " + x));
mean = Arrays.stream(testData).average();
out.println("The mean is " + mean.orElse(0));
}
项目:helper
文件:Numbers.java
@Nonnull
public static OptionalDouble parseFloat(@Nonnull String s) {
try {
return OptionalDouble.of(Float.parseFloat(s));
} catch (NumberFormatException e) {
return OptionalDouble.empty();
}
}
项目:helper
文件:Numbers.java
@Nonnull
public static OptionalDouble parseDouble(@Nonnull String s) {
try {
return OptionalDouble.of(Double.parseDouble(s));
} catch (NumberFormatException e) {
return OptionalDouble.empty();
}
}
项目:stroom-stats
文件:StroomPropertyService.java
default OptionalDouble getDoubleProperty(String name) {
Optional<String> optValue = getProperty(name);
if (optValue.isPresent()) {
return OptionalDouble.of(Double.parseDouble(optValue.get()));
} else {
return OptionalDouble.empty();
}
}
项目:Java-EX
文件:JsonPrinter.java
@SuppressWarnings("unchecked")
public JsonPrinter addJavaHandlers() {
return this
.addObjectClassHandler(Enum.class, e -> e.name())
.addObjectClassHandler(Optional.class, o -> o.orElse(null))
.addObjectClassHandler(OptionalInt.class, i -> i.isPresent() ? i.getAsInt() : null)
.addObjectClassHandler(OptionalDouble.class, i -> i.isPresent() ? i.getAsDouble() : null)
.addObjectClassHandler(OptionalLong.class, i -> i.isPresent() ? i.getAsLong() : null)
.addObjectClassHandler(Class.class, c -> c.getName())
.addObjectClassHandler(Path.class, p -> p.toString().replace('\\', '/'))
.addObjectClassHandler(File.class, f -> f.toString().replace('\\', '/'));
}
项目:guava-mock
文件:StreamsTest.java
public void testFindLast_doubleStream() {
Truth.assertThat(findLast(DoubleStream.of())).isEqualTo(OptionalDouble.empty());
Truth.assertThat(findLast(DoubleStream.of(1, 2, 3, 4, 5))).isEqualTo(OptionalDouble.of(5));
// test with a large, not-subsized Spliterator
List<Long> list =
LongStream.rangeClosed(0, 10000).boxed().collect(Collectors.toCollection(LinkedList::new));
Truth.assertThat(findLast(list.stream().mapToDouble(i -> i)))
.isEqualTo(OptionalDouble.of(10000));
// no way to find out the stream is empty without walking its spliterator
Truth.assertThat(findLast(list.stream().mapToDouble(i -> i).filter(i -> i < 0)))
.isEqualTo(OptionalDouble.empty());
}
项目:uroborosql
文件:OptionalDoublePropertyMapper.java
@Override
public OptionalDouble getValue(final JavaType type, final ResultSet rs, final int columnIndex,
final PropertyMapperManager mapperManager)
throws SQLException {
double value = rs.getDouble(columnIndex);
if (!rs.wasNull()) {
return OptionalDouble.of(value);
} else {
return OptionalDouble.empty();
}
}
项目:openjdk-jdk10
文件:BasicDouble.java
@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));
}
项目:uroborosql
文件:PropertyMapperTest.java
public PropertyMapperTestEntity(final int id) {
this.id = id;
this.name = Optional.of("name");
this.intValue = OptionalInt.of(2);
this.longValue = OptionalLong.of(3);
this.doubleValue = OptionalDouble.of(4.5);
this.dateValue = LocalDate.now();
this.datetimeValue = LocalDateTime.now();
this.enumValue = TesEnum.B_VALUE;
this.bigIntValue = BigInteger.TEN;
}
项目:uroborosql
文件:OptionalDoubleParameterMapperTest.java
@Test
public void test() {
double value = 12.3;
OptionalDoubleParameterMapper mapper = new OptionalDoubleParameterMapper();
OptionalDouble optional = OptionalDouble.of(value);
assertThat(mapper.toJdbc(optional, null, null), is(value));
}
项目:beanmother
文件:JavaOptionalConverterModuleTest.java
@Test
public void testNumberToOptionalDoubleConverter() {
converter = new JavaOptionalConverterModule.NumberToOptionalDoubleConverter();
assertTrue(converter.canHandle(1l, TypeToken.of(OptionalDouble.class)));
assertFalse(converter.canHandle(1l, TypeToken.of(OptionalLong.class)));
Object result = converter.convert(1l, TypeToken.of(OptionalDouble.class));
assertTrue(result instanceof OptionalDouble);
assertEquals(1, ((OptionalDouble) result).getAsDouble(), 0.01);
}
项目:jdk8u-jdk
文件:LongPipeline.java
@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();
}
项目:jdk8u-jdk
文件:IntPipeline.java
@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();
}
项目:SoftUni
文件:p04_AverageOfDoubles.java
public static void main(String[] args) throws IOException {
/*double[] strNums = Arrays.stream(reader.readLine().split("\\s+"))
.mapToDouble(Double::parseDouble).toArray();*/
OptionalDouble average = Arrays.stream(reader.readLine().split("\\s+"))
.filter(n -> !n.isEmpty())
.mapToDouble(Double::valueOf)
.average();
System.out.printf((average.isPresent() ?
String.format("%.2f",average.getAsDouble()) :
"No match"));
}
项目:SoftUni
文件:p05_MinEvenNumber.java
public static void main(String[] args) throws IOException {
OptionalDouble min = Arrays.stream(reader.readLine().split("\\s+"))
.filter(n -> !n.isEmpty())
.mapToDouble(Double::valueOf)
.filter(n -> n % 2 == 0)
.min();
if(min.isPresent()) System.out.printf("%.2f%n", min.getAsDouble());
else System.out.println("No match");
}
项目:openjdk-jdk10
文件:LongPipeline.java
@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();
}
项目:GitHub
文件:OptionalTest.java
public void test_optionalDouble_present() throws Exception {
String text = JSON.toJSONString(OptionalDouble.empty());
Assert.assertEquals("null", text);
}
项目:GitHub
文件:CompactOptionalDouble.java
@Encoding.Expose
OptionalDouble get() {
return present
? OptionalDouble.of(value)
: OptionalDouble.empty();
}
项目:GitHub
文件:UsingAllOptionals.java
@Value.Parameter
OptionalDouble d1();
项目:GitHub
文件:JdkOptionals.java
@Value.Parameter
OptionalDouble d1();
项目:openjdk-jdk10
文件:BasicDouble.java
@Test(expectedExceptions=ObscureException.class)
public void testEmptyOrElseThrow() throws Exception {
OptionalDouble empty = OptionalDouble.empty();
double got = empty.orElseThrow(ObscureException::new);
}
项目:GitHub
文件:UseCompactOptionals.java
@Value.Parameter
OptionalDouble d();
项目:Java-EE-8-Sampler
文件:OptionalDoubleExample.java
public OptionalDoubleExample(Double value) {
this.value = OptionalDouble.of(value);
}
项目:ProjectAres
文件:PointProviderLocation.java
public PointProviderLocation(World world, Vec3 position) {
super(world, position);
this.yaw = this.pitch = OptionalDouble.empty();
}
项目:ProjectAres
文件:PointProviderLocation.java
void clearYaw() {
this.yaw = OptionalDouble.empty();
}