java.util.OptionalDouble Java Examples

The following examples show how to use java.util.OptionalDouble. 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: DenseLocalDateDoubleTimeSeriesTest.java    From Strata with Apache License 2.0 6 votes vote down vote up
@Test
public void test_intersection_withSomeMatchingElements() {

  LocalDateDoubleTimeSeries series1 =
      LocalDateDoubleTimeSeries.builder().putAll(DATES_2015_1_WEEK, VALUES_1_WEEK).build();

  Map<LocalDate, Double> updates = ImmutableMap.of(
      DATE_2015_01_02, 1.0,
      DATE_2015_01_05, 1.1,
      DATE_2015_01_08, 1.2,
      DATE_2015_01_09, 1.3,
      DATE_2015_01_12, 1.4);

  LocalDateDoubleTimeSeries series2 =
      LocalDateDoubleTimeSeries.builder()
          .putAll(updates)
          .build();

  LocalDateDoubleTimeSeries test = series1.intersection(series2, Double::sum);
  assertThat(test.size()).isEqualTo(3);
  assertThat(test.get(DATE_2015_01_05)).isEqualTo(OptionalDouble.of(11.1));
  assertThat(test.get(DATE_2015_01_08)).isEqualTo(OptionalDouble.of(14.2));
  assertThat(test.get(DATE_2015_01_09)).isEqualTo(OptionalDouble.of(15.3));
}
 
Example #2
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 #3
Source File: JdkOptionalTest.java    From immutables with Apache License 2.0 6 votes vote down vote up
@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());
}
 
Example #4
Source File: DenseLocalDateDoubleTimeSeriesTest.java    From Strata with Apache License 2.0 6 votes vote down vote up
@ParameterizedTest
@MethodSource("data_headSeries")
public void test_headSeries(int count, int[] expected) {

  LocalDateDoubleTimeSeries base =
      LocalDateDoubleTimeSeries.builder().putAll(DATES_2015_1_WEEK, VALUES_1_WEEK).build();
  LocalDateDoubleTimeSeries test = base.headSeries(count);
  assertThat(test.size()).isEqualTo(expected.length);
  for (int i = 0; i < DATES_2015_1_WEEK.size(); i++) {
    if (Arrays.binarySearch(expected, i) >= 0) {
      assertThat(test.get(DATES_2015_1_WEEK.get(i))).isEqualTo(OptionalDouble.of(VALUES_1_WEEK.get(i)));
    } else {
      assertThat(test.get(DATES_2015_1_WEEK.get(i))).isEqualTo(OptionalDouble.empty());
    }
  }
}
 
Example #5
Source File: RegionSplitHelper.java    From bboxdb with Apache License 2.0 6 votes vote down vote up
/**
 * Needs the region a split?
 * @param region
 * @return
 * @throws BBoxDBException 
 */
public static boolean isRegionOverflow(final DistributionRegion region) throws BBoxDBException {
	
	// Is the data of the parent completely distributed?
	if(! isParentDataRedistributed(region)) {
		return false;
	}
	
	final OptionalDouble sizeOfRegionInMB = StatisticsHelper.getAndUpdateStatistics(region);

	if(! sizeOfRegionInMB.isPresent()) {
		return false;
	}
	
	try {			
		final long maxSize = getConfiguredRegionMaxSize(region);
		return (sizeOfRegionInMB.getAsDouble() > maxSize);
	} catch (ZookeeperException | ZookeeperNotFoundException e) {
		throw new BBoxDBException(e);
	} 
}
 
Example #6
Source File: DoublePipeline.java    From TencentKona-8 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 #7
Source File: MetastoreHiveStatisticsProvider.java    From presto with Apache License 2.0 6 votes vote down vote up
public static OptionalDouble convertPartitionValueToDouble(Type type, Object value)
{
    if (type.equals(BIGINT) || type.equals(INTEGER) || type.equals(SMALLINT) || type.equals(TINYINT)) {
        return OptionalDouble.of((Long) value);
    }
    if (type.equals(DOUBLE)) {
        return OptionalDouble.of((Double) value);
    }
    if (type.equals(REAL)) {
        return OptionalDouble.of(intBitsToFloat(((Long) value).intValue()));
    }
    if (type instanceof DecimalType) {
        DecimalType decimalType = (DecimalType) type;
        if (isShortDecimal(decimalType)) {
            return OptionalDouble.of(parseDouble(Decimals.toString((Long) value, decimalType.getScale())));
        }
        if (isLongDecimal(decimalType)) {
            return OptionalDouble.of(parseDouble(Decimals.toString((Slice) value, decimalType.getScale())));
        }
        throw new IllegalArgumentException("Unexpected decimal type: " + decimalType);
    }
    if (type.equals(DATE)) {
        return OptionalDouble.of((Long) value);
    }
    return OptionalDouble.empty();
}
 
Example #8
Source File: MinMaxTests.java    From morpheus-core with Apache License 2.0 6 votes vote down vote up
@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);
}
 
Example #9
Source File: BasicDouble.java    From jdk8u60 with GNU General Public License v2.0 6 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(); });
    assertEquals(2.0, empty.orElse(2.0));
    assertEquals(2.0, empty.orElseGet(()-> 2.0));
}
 
Example #10
Source File: ForwardOvernightCompoundedAnnualRateComputationFn.java    From Strata with Apache License 2.0 5 votes vote down vote up
private double valuationCompositionFactor() {
  LocalDate currentFixing = nextFixing;
  LocalDate currentPublication = computation.calculatePublicationFromFixing(currentFixing);
  if (rates.getValuationDate().equals(currentPublication) && !(currentFixing.isAfter(lastFixing))) {
    OptionalDouble fixedRate = indexFixingDateSeries.get(currentFixing);
    if (fixedRate.isPresent()) {
      nextFixing = computation.getFixingCalendar().next(nextFixing);
      LocalDate effectiveDate = computation.calculateEffectiveFromFixing(currentFixing);
      LocalDate maturityDate = computation.calculateMaturityFromEffective(effectiveDate);
      double accrualFactor = dayCount.yearFraction(effectiveDate, maturityDate);
      return Math.pow(1.0d + fixedRate.getAsDouble(), accrualFactor);
    }
  }
  return 1.0d;
}
 
Example #11
Source File: TestMemoryPagesStore.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test(expectedExceptions = PrestoException.class)
public void testTryToReadFromEmptyTable()
{
    createTable(0L, 0L);
    assertEquals(pagesStore.getPages(0L, 0, 1, ImmutableList.of(0), 0, OptionalLong.empty(), OptionalDouble.empty()), ImmutableList.of());
    pagesStore.getPages(0L, 0, 1, ImmutableList.of(0), 42, OptionalLong.empty(), OptionalDouble.empty());
}
 
Example #12
Source File: NodeMgr.java    From aion with MIT License 5 votes vote down vote up
private void timeoutActive(long now) {
    OptionalDouble average =
            activeNodes.values().stream().mapToLong(n -> now - n.getTimestamp()).average();
    this.avgLatency = (int) average.orElse(0);
    long timeout = ((long) average.orElse(4000)) * 5;
    timeout = Math.max(MIN_TIMEOUT_ACTIVE_NODES, Math.min(timeout, MAX_TIMEOUT_ACTIVE_NODES));
    if (p2pLOG.isDebugEnabled()) {
        p2pLOG.debug("<average-delay={}ms>", this.avgLatency);
    }

    try {
        Iterator<Map.Entry<Integer, INode>> it = activeNodes.entrySet().iterator();
        while (it.hasNext()) {
            Map.Entry<Integer, INode> entry = it.next();
            INode node = entry.getValue();
            if (now - node.getTimestamp() > timeout) {
                p2pMgr.closeSocket(node.getChannel(), "active-timeout ip=" + node.getIpStr());
                it.remove();
            } else if (!node.getChannel().isConnected()) {
                p2pMgr.closeSocket(
                        node.getChannel(),
                        "channel-already-closed node="
                                + node.getIdShort()
                                + " ip="
                                + node.getIpStr());
                it.remove();
            }
        }
    } catch (IllegalStateException e) {
        p2pLOG.info("<timeoutActive IllegalStateException>", e);
    }
}
 
Example #13
Source File: SimpleIborIndexRates.java    From Strata with Apache License 2.0 5 votes vote down vote up
private double historicRate(IborIndexObservation observation) {
  LocalDate fixingDate = observation.getFixingDate();
  OptionalDouble fixedRate = fixings.get(fixingDate);
  if (fixedRate.isPresent()) {
    return fixedRate.getAsDouble();
  } else if (fixingDate.isBefore(getValuationDate())) { // the fixing is required
    if (fixings.isEmpty()) {
      throw new IllegalArgumentException(
          Messages.format("Unable to get fixing for {} on date {}, no time-series supplied", index, fixingDate));
    }
    throw new IllegalArgumentException(Messages.format("Unable to get fixing for {} on date {}", index, fixingDate));
  } else {
    return rateIgnoringFixings(observation);
  }
}
 
Example #14
Source File: SparseLocalDateDoubleTimeSeriesTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_combineWith_intersectionWithSomeMatchingElements() {
  LocalDateDoubleTimeSeries series1 = LocalDateDoubleTimeSeries.builder().putAll(DATES_2010_14, VALUES_10_14).build();
  List<LocalDate> dates2 = dates(DATE_2010_01_01, DATE_2011_06_01, DATE_2012_01_01, DATE_2013_06_01, DATE_2014_01_01);
  List<Double> values2 = values(1.0, 1.1, 1.2, 1.3, 1.4);
  LocalDateDoubleTimeSeries series2 = LocalDateDoubleTimeSeries.builder().putAll(dates2, values2).build();

  LocalDateDoubleTimeSeries test = series1.intersection(series2, Double::sum);
  assertThat(test.size()).isEqualTo(3);
  assertThat(test.get(DATE_2010_01_01)).isEqualTo(OptionalDouble.of(11.0));
  assertThat(test.get(DATE_2012_01_01)).isEqualTo(OptionalDouble.of(13.2));
  assertThat(test.get(DATE_2014_01_01)).isEqualTo(OptionalDouble.of(15.4));
}
 
Example #15
Source File: Metrics.java    From presto with Apache License 2.0 5 votes vote down vote up
public static Metric distinctValuesCount(String columnName)
{
    return new Metric()
    {
        @Override
        public OptionalDouble getValueFromPlanNodeEstimate(PlanNodeStatsEstimate planNodeStatsEstimate, StatsContext statsContext)
        {
            return asOptional(getSymbolStatistics(planNodeStatsEstimate, columnName, statsContext).getDistinctValuesCount());
        }

        @Override
        public OptionalDouble getValueFromAggregationQueryResult(Object value)
        {
            return OptionalDouble.of(((Number) value).doubleValue());
        }

        @Override
        public String getComputingAggregationSql()
        {
            return "count(distinct " + columnName + ")";
        }

        @Override
        public String toString()
        {
            return "distinctValuesCount(\"" + columnName + "\")";
        }
    };
}
 
Example #16
Source File: MetricComparison.java    From presto with Apache License 2.0 5 votes vote down vote up
private String print(OptionalDouble value)
{
    if (value.isEmpty()) {
        return "UNKNOWN";
    }
    return String.valueOf(value.getAsDouble());
}
 
Example #17
Source File: TestClusterMemoryLeakDetector.java    From presto with Apache License 2.0 5 votes vote down vote up
private static BasicQueryInfo createQueryInfo(String queryId, QueryState state)
{
    return new BasicQueryInfo(
            new QueryId(queryId),
            TEST_SESSION.toSessionRepresentation(),
            Optional.of(new ResourceGroupId("global")),
            state,
            GENERAL_POOL,
            true,
            URI.create("1"),
            "",
            Optional.empty(),
            Optional.empty(),
            new BasicQueryStats(
                    DateTime.parse("1991-09-06T05:00-05:30"),
                    DateTime.parse("1991-09-06T05:01-05:30"),
                    Duration.valueOf("8m"),
                    Duration.valueOf("7m"),
                    Duration.valueOf("34m"),
                    13,
                    14,
                    15,
                    100,
                    DataSize.valueOf("21GB"),
                    22,
                    23,
                    DataSize.valueOf("23GB"),
                    DataSize.valueOf("24GB"),
                    DataSize.valueOf("25GB"),
                    DataSize.valueOf("26GB"),
                    Duration.valueOf("23m"),
                    Duration.valueOf("24m"),
                    true,
                    ImmutableSet.of(WAITING_FOR_MEMORY),
                    OptionalDouble.of(20)),
            null,
            null);
}
 
Example #18
Source File: DeploymentActivity.java    From vespa with Apache License 2.0 5 votes vote down vote up
public static DeploymentActivity create(Optional<Instant> queriedAt, Optional<Instant> writtenAt,
                                        OptionalDouble lastQueriesPerSecond, OptionalDouble lastWritesPerSecond) {
    if (queriedAt.isEmpty() && writtenAt.isEmpty()) {
        return none;
    }
    return new DeploymentActivity(queriedAt, writtenAt, lastQueriesPerSecond, lastWritesPerSecond);
}
 
Example #19
Source File: LongPipeline.java    From jdk8u_jdk 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 #20
Source File: MockManagedQueryExecution.java    From presto with Apache License 2.0 5 votes vote down vote up
@Override
public BasicQueryInfo getBasicQueryInfo()
{
    return new BasicQueryInfo(
            new QueryId("test"),
            session.toSessionRepresentation(),
            Optional.empty(),
            state,
            new MemoryPoolId("test"),
            !state.isDone(),
            URI.create("http://test"),
            "SELECT 1",
            Optional.empty(),
            Optional.empty(),
            new BasicQueryStats(
                    new DateTime(1),
                    new DateTime(2),
                    new Duration(3, NANOSECONDS),
                    new Duration(4, NANOSECONDS),
                    new Duration(5, NANOSECONDS),
                    6,
                    7,
                    8,
                    9,
                    DataSize.ofBytes(14),
                    15,
                    16.0,
                    memoryUsage,
                    memoryUsage,
                    DataSize.ofBytes(19),
                    DataSize.ofBytes(20),
                    cpuUsage,
                    new Duration(22, NANOSECONDS),
                    false,
                    ImmutableSet.of(),
                    OptionalDouble.empty()),
            null,
            null);
}
 
Example #21
Source File: APredictionPerformanceMeasure.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
protected double averageInstanceWiseScore(final List<E> expected, final List<A> actual, final IDeterministicInstancePredictionPerformanceMeasure<A, E> subMeasure) {
	OptionalDouble res = IntStream.range(0, expected.size()).mapToDouble(x -> subMeasure.score(expected.get(x), actual.get(x))).average();
	if (res.isPresent()) {
		return res.getAsDouble();
	} else {
		throw new IllegalStateException("The submeasure could not be aggregated.");
	}
}
 
Example #22
Source File: MetricComparator.java    From presto with Apache License 2.0 5 votes vote down vote up
static List<MetricComparison> getMetricComparisons(String query, QueryRunner runner, List<Metric> metrics)
{
    List<OptionalDouble> estimatedValues = getEstimatedValues(metrics, query, runner);
    List<OptionalDouble> actualValues = getActualValues(metrics, query, runner);

    ImmutableList.Builder<MetricComparison> metricComparisons = ImmutableList.builder();
    for (int i = 0; i < metrics.size(); ++i) {
        //noinspection unchecked
        metricComparisons.add(new MetricComparison(
                metrics.get(i),
                estimatedValues.get(i),
                actualValues.get(i)));
    }
    return metricComparisons.build();
}
 
Example #23
Source File: RankLoss.java    From AILibs with GNU Affero General Public License v3.0 5 votes vote down vote up
@Override
public double loss(final List<? extends int[]> expected, final List<? extends IMultiLabelClassification> actual) {
	this.checkConsistency(expected, actual);

	OptionalDouble res = IntStream.range(0, expected.size()).mapToDouble(x -> this.rankingLoss(expected.get(x), actual.get(x))).average();
	if (res.isPresent()) {
		return res.getAsDouble();
	} else {
		throw new IllegalStateException("The ranking loss could not be averaged across all the instances.");
	}
}
 
Example #24
Source File: LongPipeline.java    From openjdk-8-source 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 #25
Source File: TestMetastoreHiveStatisticsProvider.java    From presto with Apache License 2.0 5 votes vote down vote up
@Test
public void testCalculateAverageRowsPerPartition()
{
    assertThat(calculateAverageRowsPerPartition(ImmutableList.of())).isEmpty();
    assertThat(calculateAverageRowsPerPartition(ImmutableList.of(PartitionStatistics.empty()))).isEmpty();
    assertThat(calculateAverageRowsPerPartition(ImmutableList.of(PartitionStatistics.empty(), PartitionStatistics.empty()))).isEmpty();
    assertEquals(calculateAverageRowsPerPartition(ImmutableList.of(rowsCount(10))), OptionalDouble.of(10));
    assertEquals(calculateAverageRowsPerPartition(ImmutableList.of(rowsCount(10), PartitionStatistics.empty())), OptionalDouble.of(10));
    assertEquals(calculateAverageRowsPerPartition(ImmutableList.of(rowsCount(10), rowsCount(20))), OptionalDouble.of(15));
    assertEquals(calculateAverageRowsPerPartition(ImmutableList.of(rowsCount(10), rowsCount(20), PartitionStatistics.empty())), OptionalDouble.of(15));
}
 
Example #26
Source File: OptionalStruct.java    From drift with Apache License 2.0 5 votes vote down vote up
public OptionalStruct()
{
    aBooleanOptional = Optional.empty();
    aByteOptional = Optional.empty();
    aShortOptional = Optional.empty();
    aIntegerOptional = Optional.empty();
    aLongOptional = Optional.empty();
    aDoubleOptional = Optional.empty();
    aStringOptional = Optional.empty();
    aStructOptional = Optional.empty();
    aEnumOptional = Optional.empty();
    aCustomEnumOptional = Optional.empty();

    aOptionalDouble = OptionalDouble.empty();
    aOptionalInt = OptionalInt.empty();
    aOptionalLong = OptionalLong.empty();

    aListBooleanOptional = Optional.empty();
    aListByteOptional = Optional.empty();
    aListShortOptional = Optional.empty();
    aListIntegerOptional = Optional.empty();
    aListLongOptional = Optional.empty();
    aListDoubleOptional = Optional.empty();
    aListStringOptional = Optional.empty();
    aListStructOptional = Optional.empty();
    aListEnumOptional = Optional.empty();
    aListCustomEnumOptional = Optional.empty();
}
 
Example #27
Source File: Mappings.java    From immutables with Apache License 2.0 5 votes vote down vote up
private static String elasticType(Type type) {
  Objects.requireNonNull(type, "type");
  if (type instanceof ParameterizedType) {
    ParameterizedType parametrized = (ParameterizedType) type;
    if (parametrized.getActualTypeArguments().length == 1) {
      // unwrap
      return elasticType(parametrized.getActualTypeArguments()[0]);
    }
  }
  if (type == String.class || type == Character.class || type == char.class) {
    return "keyword";
  } else if (type == Boolean.class || type == boolean.class) {
    return "boolean";
  } else if (type == Byte.class || type == byte.class) {
    return "byte";
  } else if (type == Short.class || type == short.class) {
    return "short";
  } else if (type == Integer.class || type == int.class || type == OptionalInt.class) {
    return "integer";
  } else if (type == Long.class || type == long.class || type == OptionalLong.class) {
    return "long";
  } else if (type == Double.class || type == double.class || type == OptionalDouble.class) {
    return "double";
  } else if (type == Float.class || type == float.class) {
    return "float";
  } else if (type == LocalDate.class || type == Instant.class || type == LocalDateTime.class || type == Date.class) {
    return "date";
  } else if (type instanceof Class && ((Class) type).isEnum()) {
    return "keyword";
  } else if (type == BigDecimal.class) {
    return "double"; // precession loss ?
  } else if (type == BigInteger.class) {
    return "long"; // precession loss ?
  }

  throw new IllegalArgumentException("Don't know how to map " + type);
}
 
Example #28
Source File: Main.java    From Java-Coding-Problems with MIT License 5 votes vote down vote up
public static void main(String[] args) {

        // Avoid
        Optional<Integer> priceInt1 = Optional.of(50);
        Optional<Long> priceLong1 = Optional.of(50L);
        Optional<Double> priceDouble1 = Optional.of(49.99d);

        // Prefer
        OptionalInt priceInt2 = OptionalInt.of(50);              // unwrap via getAsInt()
        OptionalLong priceLong2 = OptionalLong.of(50L);          // unwrap via getAsLong()
        OptionalDouble priceDouble2 = OptionalDouble.of(49.99d); // unwrap via getAsDouble()
    }
 
Example #29
Source File: InflationRateCalculationTest.java    From Strata with Apache License 2.0 5 votes vote down vote up
@Test
public void test_of_firstIndexValue() {
  InflationRateCalculation test1 = InflationRateCalculation.of(CH_CPI, 3, MONTHLY, 123d);
  assertThat(test1.getIndex()).isEqualTo(CH_CPI);
  assertThat(test1.getLag()).isEqualTo(Period.ofMonths(3));
  assertThat(test1.getIndexCalculationMethod()).isEqualTo(MONTHLY);
  assertThat(test1.getFirstIndexValue()).isEqualTo(OptionalDouble.of(123d));
  assertThat(test1.getGearing()).isEqualTo(Optional.empty());
  assertThat(test1.getType()).isEqualTo(SwapLegType.INFLATION);
}
 
Example #30
Source File: BasicDouble.java    From dragonwell8_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));
}