java.util.stream.DoubleStream Java Examples

The following examples show how to use java.util.stream.DoubleStream. 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: JmxReducers.java    From datakernel with Apache License 2.0 6 votes vote down vote up
@Nullable
private static Number reduceNumbers(List<? extends Number> list,
		Function<DoubleStream, Double> opDouble, Function<LongStream, Long> opLong) {
	list = list.stream().filter(Objects::nonNull).collect(toList());

	if (list.isEmpty()) return null;

	Class<?> numberClass = list.get(0).getClass();
	if (isFloatingPointNumber(numberClass)) {
		return convert(numberClass,
				opDouble.apply(list.stream().mapToDouble(Number::doubleValue)));
	} else if (isIntegerNumber(numberClass)) {
		return convert(numberClass,
				opLong.apply(list.stream().mapToLong(Number::longValue)));
	} else {
		throw new IllegalArgumentException(
				"Unsupported objects of type: " + numberClass.getName());
	}
}
 
Example #2
Source File: DoubleSupplier.java    From latexdraw with GNU General Public License v3.0 6 votes vote down vote up
@Override
public List<PotentialAssignment> getValueSources(final ParameterSignature sig) {
	final DoubleData doubledata = sig.getAnnotation(DoubleData.class);
	DoubleStream stream = Arrays.stream(doubledata.vals());

	if(doubledata.angle()) {
		stream = DoubleStream.of(0d, Math.PI / 2d, Math.PI, 3d * Math.PI / 2d, 2d * Math.PI, -Math.PI / 2d, -Math.PI,
			-3d * Math.PI / 2d, -2d * Math.PI, 1.234, -1.234, 3d * Math.PI, -3d * Math.PI);
	}

	if(doubledata.bads()) {
		stream = DoubleStream.concat(stream, DoubleStream.of(Double.NaN, Double.NEGATIVE_INFINITY, Double.POSITIVE_INFINITY));
	}

	return stream.mapToObj(i -> PotentialAssignment.forValue("", i)).collect(Collectors.toList());
}
 
Example #3
Source File: SomaticPeakFactory.java    From hmftools with GNU General Public License v3.0 6 votes vote down vote up
@NotNull
static List<SomaticPeak> findPeaks(@NotNull final List<Double> sample) {
    final KernelEstimator estimator = new KernelEstimator(0.001, KERNEL_BANDWIDTH);
    sample.forEach(x -> estimator.addValue(x, 1.0D));

    final double[] vafs = IntStream.rangeClosed(0, 51).mapToDouble(x -> x / 100d).toArray();
    final double[] densities = DoubleStream.of(vafs).map(estimator::getProbability).toArray();

    final List<SomaticPeak> results = Lists.newArrayList();
    for (int i = 1; i < densities.length - 1; i++) {
        double density = densities[i];
        if (Doubles.greaterThan(density, densities[i - 1]) && Doubles.greaterThan(density, densities[i + 1])) {
            final double alleleFrequency = vafs[i];
            final int peakCount = count(alleleFrequency, sample);
            final SomaticPeak peak = ImmutableSomaticPeak.builder().alleleFrequency(alleleFrequency).count(peakCount).build();
            LOGGER.info("Discovered peak {}", peak);
            results.add(peak);
        }
    }

    return results;
}
 
Example #4
Source File: ConcatOpTest.java    From jdk8u-dev-jdk with GNU General Public License v2.0 6 votes vote down vote up
public void testDoubleSize() {
    assertSized(DoubleStream.concat(
            IntStream.range(0, Integer.MAX_VALUE).mapToDouble(i -> i),
            IntStream.range(0, Integer.MAX_VALUE).mapToDouble(i -> i)));

    assertUnsized(DoubleStream.concat(
            LongStream.range(0, Long.MAX_VALUE).mapToDouble(i -> i),
            LongStream.range(0, Long.MAX_VALUE).mapToDouble(i -> i)));

    assertUnsized(DoubleStream.concat(
            LongStream.range(0, Long.MAX_VALUE).mapToDouble(i -> i),
            DoubleStream.iterate(0, i -> i + 1)));

    assertUnsized(DoubleStream.concat(
            DoubleStream.iterate(0, i -> i + 1),
            LongStream.range(0, Long.MAX_VALUE).mapToDouble(i -> i)));
}
 
Example #5
Source File: NumericStreams.java    From Learn-Java-12-Programming with MIT License 6 votes vote down vote up
private static void boxed(){
    //IntStream.range(1, 3).map(Integer::shortValue)        //compile error
    //                     .forEach(System.out::print);

    IntStream.range(1, 3).boxed().map(Integer::shortValue)
            .forEach(System.out::print);                    //prints: 12
    System.out.println();
    //LongStream.range(1, 3).map(Long::shortValue)          //compile error
    //                      .forEach(System.out::print);

    LongStream.range(1, 3).boxed().map(Long::shortValue)
            .forEach(System.out::print);                    //prints: 12
    System.out.println();
    //DoubleStream.of(1).map(Double::shortValue)            //compile error
    //                  .forEach(System.out::print);

    DoubleStream.of(1).boxed().map(Double::shortValue)
            .forEach(System.out::print);                    //prints: 1

}
 
Example #6
Source File: NDArrayNumericOpTest.java    From djl with Apache License 2.0 6 votes vote down vote up
@Test
public void testAbs() {
    try (NDManager manager = NDManager.newBaseManager()) {
        double[] data = {1.0, -2.12312, -3.5784, -4.0, 5.0, -223.23423};
        NDArray array = manager.create(data);
        data = DoubleStream.of(data).map(Math::abs).toArray();
        NDArray expected = manager.create(data);
        Assertions.assertAlmostEquals(array.abs(), expected);
        // test multi-dim
        data = new double[] {1.2, 98.34, 2.34, -0.456, 2, -22};
        array = manager.create(data, new Shape(2, 1, 1, 3));
        data = DoubleStream.of(data).map(Math::abs).toArray();
        expected = manager.create(data, new Shape(2, 1, 1, 3));
        Assertions.assertAlmostEquals(array.abs(), expected);
        // test scalar
        array = manager.create(-0.00001f);
        expected = manager.create(0.00001f);
        Assertions.assertAlmostEquals(array.abs(), expected);
        // test zero-dim
        array = manager.create(new Shape(0, 0, 2, 0));
        Assert.assertEquals(array.abs(), array);
    }
}
 
Example #7
Source File: BoxCountTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
@Test
public void testAllForeground() {
	// SETUP
	final double scalingPow = DoubleStream.generate(() -> SCALING).limit(
		DIMENSIONS).reduce((i, j) -> i * j).orElse(0);
	final double[] expectedCounts = DoubleStream.iterate(1.0, i -> i *
		scalingPow).map(Math::log).limit(ITERATIONS).toArray();
	final Img<BitType> img = ArrayImgs.bits(TEST_DIMS);
	img.forEach(BitType::setOne);

	// EXECUTE
	final List<ValuePair<DoubleType, DoubleType>> points = ops.topology()
		.boxCount(img, MAX_SIZE, MIN_SIZE, SCALING);

	// VERIFY
	for (int i = 0; i < ITERATIONS; i++) {
		assertEquals(EXPECTED_SIZES[i], points.get(i).a.get(), 1e-12);
		assertEquals(expectedCounts[i], points.get(i).b.get(), 1e-12);
	}
}
 
Example #8
Source File: BoxCountTest.java    From imagej-ops with BSD 2-Clause "Simplified" License 6 votes vote down vote up
/**
 * Test box counting with a hyper cube and one grid translation (should find a
 * better fit than in @see {@link #testHyperCube()})
 */
@Test
public void testHyperCubeTranslations() {
	final double[] expectedSizes = DoubleStream.of(4, 2, 1).map(i -> -Math.log(
		i)).toArray();
	final double[] expectedCounts = DoubleStream.of(1, 1, 16).map(Math::log)
		.toArray();
	final Img<BitType> img = ArrayImgs.bits(4, 4, 4, 4);
	final IntervalView<BitType> hyperView = Views.offsetInterval(img,
		new long[] { 1, 1, 1, 1 }, new long[] { 2, 2, 2, 2 });
	hyperView.forEach(BitType::setOne);

	// EXECUTE
	final List<ValuePair<DoubleType, DoubleType>> points = ops.topology()
		.boxCount(img, 4L, 1L, 2.0, 1L);

	// VERIFY
	for (int i = 0; i < expectedSizes.length; i++) {
		assertEquals(expectedSizes[i], points.get(i).a.get(), 1e-12);
		assertEquals(expectedCounts[i], points.get(i).b.get(), 1e-12);
	}
}
 
Example #9
Source File: HDF5PCACoveragePoNCreationUtilsUnitTest.java    From gatk-protected with BSD 3-Clause "New" or "Revised" License 6 votes vote down vote up
@Test(dataProvider = "readCountOnlyWithDiverseShapeData")
public void testCalculateReducedPanelAndPInversesUsingJollifesRule(final ReadCountCollection readCounts) {
    final JavaSparkContext ctx = SparkContextFactory.getTestSparkContext();
    final ReductionResult result = HDF5PCACoveragePoNCreationUtils.calculateReducedPanelAndPInverses(readCounts, OptionalInt.empty(), NULL_LOGGER, ctx);
    final RealMatrix counts = readCounts.counts();
    Assert.assertNotNull(result);
    Assert.assertNotNull(result.getPseudoInverse());
    Assert.assertNotNull(result.getReducedCounts());
    Assert.assertNotNull(result.getReducedPseudoInverse());
    Assert.assertNotNull(result.getAllSingularValues());
    Assert.assertEquals(counts.getColumnDimension(), result.getAllSingularValues().length);
    Assert.assertEquals(result.getReducedCounts().getRowDimension(), counts.getRowDimension());
    final int eigensamples = result.getReducedCounts().getColumnDimension();
    final Mean mean = new Mean();
    final double meanSingularValue = mean.evaluate(result.getAllSingularValues());
    final double threshold = HDF5PCACoveragePoNCreationUtils.JOLLIFES_RULE_MEAN_FACTOR * meanSingularValue;
    final int expectedEigensamples = (int) DoubleStream.of(result.getAllSingularValues()).filter(d -> d >= threshold).count();
    Assert.assertTrue(eigensamples <= counts.getColumnDimension());
    Assert.assertEquals(eigensamples, expectedEigensamples);
    assertPseudoInverse(counts, result.getPseudoInverse());
    assertPseudoInverse(result.getReducedCounts(), result.getReducedPseudoInverse());
}
 
Example #10
Source File: SinCosPerformance.java    From commons-numbers with Apache License 2.0 6 votes vote down vote up
@Override
protected double[] createNumbers(SplittableRandom rng) {
    DoubleSupplier generator;
    if ("pi".equals(type)) {
        generator = () -> rng.nextDouble() * 2 * Math.PI - Math.PI;
    } else if ("pi/2".equals(type)) {
        generator = () -> rng.nextDouble() * Math.PI - Math.PI / 2;
    } else if ("random".equals(type)) {
        generator = () -> createRandomNumber(rng);
    } else if ("edge".equals(type)) {
        generator = () -> createEdgeNumber(rng);
    } else {
        throw new IllegalStateException("Unknown number type: " + type);
    }
    return DoubleStream.generate(generator).limit(getSize()).toArray();
}
 
Example #11
Source File: NumericStreams.java    From Java-11-Cookbook-Second-Edition with MIT License 6 votes vote down vote up
private static void sumAndAverage() {

        System.out.println();
        int sum = IntStream.empty().sum();
        System.out.println(sum);  //prints: 0
        sum = IntStream.range(1, 3).sum();
        System.out.println(sum);  //prints: 3
        double av = IntStream.empty().average().orElse(0);
        System.out.println(av);   //prints: 0.0
        av = IntStream.range(1, 3).average().orElse(0);
        System.out.println(av);   //prints: 1.5

        long suml = LongStream.range(1, 3).sum();
        System.out.println(suml);  //prints: 3
        double avl = LongStream.range(1, 3).average().orElse(0);
        System.out.println(avl);   //prints: 1.5

        double sumd = DoubleStream.of(1, 2).sum();
        System.out.println(sumd);  //prints: 3.0
        double avd = DoubleStream.of(1, 2).average().orElse(0);
        System.out.println(avd);   //prints: 1.5

    }
 
Example #12
Source File: InfiniteStreamWithLimitOpTest.java    From jdk8u_jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "DoubleStream.limit")
public void testDoubleUnorderedIteration(String description, UnaryOperator<DoubleStream> fs) {
    // Source is a right-balanced tree of infinite size
    TestData.OfDouble iterator = TestData.Factory.ofDoubleSupplier(
            "[1.0, 2.0, 3.0, ...]", () -> DoubleStream.iterate(1, i -> i + 1));

    // Ref
    withData(iterator).
            stream(s -> fs.apply(s.unordered())).
            resultAsserter(unorderedAsserter()).
            exercise();
}
 
Example #13
Source File: FisherExactTest.java    From gatk with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
/**
 * Computes the 2-sided pvalue of the Fisher's exact test on a normalized table that ensures that the sum of
 * all four entries is less than 2 * 200.
 */
public static double twoSidedPValue(final int[][] normalizedTable) {
    Utils.nonNull(normalizedTable);
    Utils.validateArg(normalizedTable.length == 2, () -> "input must be 2x2 " + Arrays.deepToString(normalizedTable));
    Utils.validateArg(normalizedTable[0] != null && normalizedTable[0].length == 2, () -> "input must be 2x2 " + Arrays.deepToString(normalizedTable));
    Utils.validateArg(normalizedTable[1] != null && normalizedTable[1].length == 2, () -> "input must be 2x2 " + Arrays.deepToString(normalizedTable));

    //Note: this implementation follows the one in R base package
    final int[][] x= normalizedTable;
    final int m = x[0][0] + x[0][1];
    final int n = x[1][0] + x[1][1];
    final int k = x[0][0] + x[1][0];
    final int lo = Math.max(0, k - n);
    final int hi = Math.min(k, m);
    final IndexRange support = new IndexRange(lo, hi + 1);

    if (support.size() <= 1){     //special case, support has only one value
        return 1.0;
    }

    final AbstractIntegerDistribution dist = new HypergeometricDistribution(null, m+n, m, k);
    final double[] logds = support.mapToDouble(dist::logProbability);
    final double threshold = logds[x[0][0] - lo] * REL_ERR;
    final double[] log10ds = DoubleStream.of(logds).filter(d -> d <= threshold).map(MathUtils::logToLog10).toArray();
    final double pValue = MathUtils.sumLog10(log10ds);

    // min is necessary as numerical precision can result in pValue being slightly greater than 1.0
    return Math.min(pValue, 1.0);
}
 
Example #14
Source File: InfiniteStreamWithLimitOpTest.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "DoubleStream.limit")
public void testDoubleSubsizedWithRange(String description, UnaryOperator<DoubleStream> fs) {
    // Range is [0, 2^53), splits are SUBSIZED
    // Such a size will induce out of memory errors for incorrect
    // slice implementations
    withData(doubles()).
            stream(s -> fs.apply(s)).
            without(DoubleStreamTestScenario.PAR_STREAM_TO_ARRAY_CLEAR_SIZED).
            exercise();
}
 
Example #15
Source File: DistinctOpTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
public void testOp(String name, TestData.OfRef<Integer> data) {
    Collection<Integer> result = exerciseOpsInt(
            data,
            Stream::distinct,
            IntStream::distinct,
            LongStream::distinct,
            DoubleStream::distinct);

    assertUnique(result);
    assertTrue((data.size() > 0) ? result.size() > 0 : result.size() == 0);
    assertTrue(result.size() <= data.size());
}
 
Example #16
Source File: InfiniteStreamWithLimitOpTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "DoubleStream.limit")
public void testDoubleUnorderedFinite(String description, UnaryOperator<DoubleStream> fs) {
    // Range is [0, 1L << 53), splits are SUBSIZED
    // Such a size will induce out of memory errors for incorrect
    // slice implementations
    // Upper bound ensures values mapped to doubles will be unique
    withData(doubles()).
            stream(s -> fs.apply(s.filter(i -> true).unordered())).
            resultAsserter(unorderedAsserter()).
            exercise();
}
 
Example #17
Source File: StreamBuilderTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "sizes")
public void testDoubleAfterBuilding(int size) {
    DoubleStream.Builder sb = DoubleStream.builder();
    IntStream.range(0, size).asDoubleStream().forEach(sb);
    sb.build();

    checkISE(() -> sb.accept(1));
    checkISE(() -> sb.add(1));
    checkISE(() -> sb.build());
}
 
Example #18
Source File: InfiniteStreamWithLimitOpTest.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "DoubleStream.limit")
public void testDoubleSubsizedWithRange(String description, UnaryOperator<DoubleStream> fs) {
    // Range is [0, 2^53), splits are SUBSIZED
    // Such a size will induce out of memory errors for incorrect
    // slice implementations
    withData(doubles()).
            stream(s -> fs.apply(s)).
            without(DoubleStreamTestScenario.CLEAR_SIZED_SCENARIOS).
            exercise();
}
 
Example #19
Source File: InfiniteStreamWithLimitOpTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "DoubleStream.limit")
public void testDoubleSubsizedWithRange(String description, UnaryOperator<DoubleStream> fs) {
    // Range is [0, 2^53), splits are SUBSIZED
    // Such a size will induce out of memory errors for incorrect
    // slice implementations
    withData(doubles()).
            stream(s -> fs.apply(s)).
            without(DoubleStreamTestScenario.PAR_STREAM_TO_ARRAY_CLEAR_SIZED).
            exercise();
}
 
Example #20
Source File: InfiniteStreamWithLimitOpTest.java    From openjdk-8 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "DoubleStream.limit")
public void testDoubleUnorderedGenerator(String description, UnaryOperator<DoubleStream> fs) {
    // Source is spliterator of infinite size
    TestData.OfDouble generator = TestData.Factory.ofDoubleSupplier(
            "[1.0, 1.0, ...]", () -> DoubleStream.generate(() -> 1.0));

    withData(generator).
            stream(s -> fs.apply(s.filter(i -> true).unordered())).
            exercise();
}
 
Example #21
Source File: ReadmeTest.java    From paleo with Apache License 2.0 5 votes vote down vote up
@Test
public void demo() {

    // Type-safe column identifiers
    final StringColumnId NAME = StringColumnId.of("Name");
    final CategoryColumnId COLOR = CategoryColumnId.of("Color");
    final DoubleColumnId SERVING_SIZE = DoubleColumnId.of("Serving Size (g)");

    // Convenient column creation
    StringColumn nameColumn = StringColumn.ofAll(NAME, "Banana", "Blueberry", "Lemon", "Apple");
    CategoryColumn colorColumn = CategoryColumn.ofAll(COLOR, "Yellow", "Blue", "Yellow", "Green");
    DoubleColumn servingSizeColumn = DoubleColumn.ofAll(SERVING_SIZE, 118, 148, 83, 182);

    // Grouping columns into a data frame
    DataFrame dataFrame = DataFrame.ofAll(nameColumn, colorColumn, servingSizeColumn);

    // Typed random access to individual values (based on rowIndex / columnId)
    String lemon = dataFrame.getValueAt(2, NAME);
    double appleServingSize = dataFrame.getValueAt(3, SERVING_SIZE);

    // Typed stream-based access to all values
    DoubleStream servingSizes = servingSizeColumn.valueStream();
    double maxServingSize = servingSizes.summaryStatistics().getMax();

    // Smart column implementations
    Set<String> colors = colorColumn.getCategories();

}
 
Example #22
Source File: WhileOpTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Test(groups = { "serialization-hostile" })
public void testDoubleDefaultClose() {
    AtomicBoolean isClosed = new AtomicBoolean();
    DoubleStream s = DoubleStream.of(1, 2, 3).onClose(() -> isClosed.set(true));
    try (DoubleStream ds = DefaultMethodStreams.delegateTo(s).takeWhile(e -> e < 3)) {
        ds.count();
    }
    assertTrue(isClosed.get());
}
 
Example #23
Source File: StreamBuilderTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "sizes")
public void testDoubleAfterBuilding(int size) {
    DoubleStream.Builder sb = DoubleStream.builder();
    IntStream.range(0, size).asDoubleStream().forEach(sb);
    sb.build();

    checkISE(() -> sb.accept(1));
    checkISE(() -> sb.add(1));
    checkISE(() -> sb.build());
}
 
Example #24
Source File: StreamBuilderTest.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testDoubleSingleton() {
    TestData.OfDouble data = TestData.Factory.ofDoubleSupplier("[0, 1)", () -> DoubleStream.of(1));

    withData(data).
            stream(s -> s).
            expectedResult(Collections.singletonList(1.0)).
            exercise();

    withData(data).
            stream(s -> s.map(i -> i)).
            expectedResult(Collections.singletonList(1.0)).
            exercise();
}
 
Example #25
Source File: CountTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "DoubleStreamTestData", dataProviderClass = DoubleStreamTestDataProvider.class)
public void testOps(String name, TestData.OfDouble data) {
    AtomicLong expectedCount = new AtomicLong();
    data.stream().forEach(e -> expectedCount.incrementAndGet());

    withData(data).
            terminal(DoubleStream::count).
            expectedResult(expectedCount.get()).
            exercise();
}
 
Example #26
Source File: StreamBuilderTest.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
private void testDoubleStreamBuilder(int size, Function<Integer, DoubleStream> supplier) {
    TestData.OfDouble data = TestData.Factory.ofDoubleSupplier(String.format("[0, %d)", size),
                                                               () -> supplier.apply(size));

    withData(data).
            stream(s -> s).
            expectedResult(IntStream.range(0, size).asDoubleStream().toArray()).
            exercise();

    withData(data).
            stream(s -> s.map(i -> i)).
            expectedResult(IntStream.range(0, size).asDoubleStream().toArray()).
            exercise();
}
 
Example #27
Source File: TimeDiscretizationFromArray.java    From finmath-lib with Apache License 2.0 5 votes vote down vote up
/**
 * Constructs a time discretization using the given tick size.
 * The time discretization will be sorted. Duplicate entries are allowed if <code>allowDuplicates</code> is true, otherwise duplicate entries are removed.
 *
 * @param times A non closed and not necessarily sorted stream containing the time points.
 * @param tickSize A non-negative double representing the smallest time span distinguishable.
 * @param allowDuplicates If true, the time discretization allows duplicate entries.
 */
public TimeDiscretizationFromArray(DoubleStream times, final double tickSize, final boolean allowDuplicates) {
	timeTickSize = tickSize;
	times = times.map(this::roundToTimeTickSize);
	if(!allowDuplicates) {
		times = times.distinct();
	}
	timeDiscretization = times.sorted().toArray();
}
 
Example #28
Source File: ConcatOpTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class)
public void testOps(String name, TestData.OfRef<Integer> data) {
    exerciseOpsInt(data,
                   s -> Stream.concat(s, data.stream()),
                   s -> IntStream.concat(s, data.stream().mapToInt(Integer::intValue)),
                   s -> LongStream.concat(s, data.stream().mapToLong(Integer::longValue)),
                   s -> DoubleStream.concat(s, data.stream().mapToDouble(Integer::doubleValue)));
}
 
Example #29
Source File: StreamBuilderTest.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
private void testDoubleStreamBuilder(int size, Function<Integer, DoubleStream> supplier) {
    TestData.OfDouble data = TestData.Factory.ofDoubleSupplier(String.format("[0, %d)", size),
                                                               () -> supplier.apply(size));

    withData(data).
            stream(s -> s).
            expectedResult(IntStream.range(0, size).asDoubleStream().toArray()).
            exercise();

    withData(data).
            stream(s -> s.map(i -> i)).
            expectedResult(IntStream.range(0, size).asDoubleStream().toArray()).
            exercise();
}
 
Example #30
Source File: StreamBuilderTest.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "sizes")
public void testDoubleAfterBuilding(int size) {
    DoubleStream.Builder sb = DoubleStream.builder();
    IntStream.range(0, size).asDoubleStream().forEach(sb);
    sb.build();

    checkISE(() -> sb.accept(1));
    checkISE(() -> sb.add(1));
    checkISE(() -> sb.build());
}