public static Name makeOperator(String name, DoubleBinaryOperator dbo) { return new Name(name, toTableConsumer(stack -> { int rightCount = (int) ((Column.OfConstantDoubles) stack.removeFirst()).getValue().doubleValue(); if (stack.size() < rightCount + 1) { throw new IllegalArgumentException("Not enough inputs for " + name); } LinkedList<Column<?,?>> rights = new LinkedList<>(stack.subList(0, rightCount)); List<Column<?,?>> lefts = new ArrayList<>(stack.subList(rightCount, stack.size())); stack.clear(); for (int i = 0; i < lefts.size(); i++) { Column<?,?> right = i >= rights.size() ? rights.getFirst().clone() : rights.getFirst(); rights.addLast(rights.removeFirst()); stack.add(new Column.OfDoubles(inputs -> inputs[1].toString() + " " + inputs[0].toString() + " " + name, inputs -> range -> { OfDouble leftIterator = ((Column.OfDoubles)inputs[1]).rows().iterator(); return ((Column.OfDoubles)inputs[0]).rows().map(r -> dbo.applyAsDouble(leftIterator.nextDouble(), r)); }, right, lefts.get(i))); } }),"[n=1,:]", "Binary double operator " + name + " that operates on *n* columns at a time with fixed right-side operand."); }
public String toCsv(DateTimeFormatter dtf, NumberFormat nf) { StringBuilder sb = new StringBuilder(); sb.append(streamInReverse(peekStack()).map(Column::getHeader).collect(Collectors.joining(",","Date,","\n"))); if(getRange().isPresent()) { List<LocalDate> d = getRange().get().dates(); List<OfDouble> s = peekStack().stream().map(c -> (Column.OfDoubles) c).map(c -> c.rows()) .map(DoubleStream::iterator).collect(Collectors.toList()); for(int row = 0; row < getRange().get().size(); row++) { sb.append(d.get(row).format(dtf)).append(","); for (int col = peekStack().size() - 1; col > -1; col--) { sb.append(nf.format(s.get(col).nextDouble())); sb.append(col > 0 ? "," : "\n"); } } } return sb.toString(); }
/** * Returns a {@code float[]} array containing the elements of this stream * which are converted to floats using {@code (float)} cast operation. * * <p> * This is a terminal operation. * * @return an array containing the elements of this stream * @since 0.3.0 */ public float[] toFloatArray() { if (isParallel()) return collect(DoubleCollector.toFloatArray()); java.util.Spliterator.OfDouble spliterator = spliterator(); long size = spliterator.getExactSizeIfKnown(); FloatBuffer buf; if (size >= 0 && size <= Integer.MAX_VALUE) { buf = new FloatBuffer((int) size); spliterator.forEachRemaining((DoubleConsumer) buf::addUnsafe); } else { buf = new FloatBuffer(); spliterator.forEachRemaining((DoubleConsumer) buf::add); } return buf.toArray(); }
@Test public void testDropWhile() { assertArrayEquals(new double[] { 5, 6, 7, 8, 9, 10, 11, 12, 13, 14 }, LongStreamEx.range(100).asDoubleStream() .dropWhile(i -> i % 10 < 5).limit(10).toArray(), 0.0); assertEquals(100, LongStreamEx.range(100).asDoubleStream().sorted().dropWhile(i -> i % 10 < 0).count()); assertEquals(0, LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 10).count()); assertEquals(OptionalDouble.of(0), LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 0).findFirst()); assertEquals(OptionalDouble.empty(), LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 10).findFirst()); java.util.Spliterator.OfDouble spltr = LongStreamEx.range(100).asDoubleStream().dropWhile(i -> i % 10 < 1).spliterator(); assertTrue(spltr.tryAdvance((double x) -> assertEquals(1, x, 0.0))); Builder builder = DoubleStream.builder(); spltr.forEachRemaining(builder); assertArrayEquals(LongStreamEx.range(2, 100).asDoubleStream().toArray(), builder.build().toArray(), 0.0); }
@Override public OfDouble iterator() { return this.delegate.iterator(); }
@Override public java.util.Spliterator.OfDouble spliterator() { return this.delegate.spliterator(); }
DoubleStreamEx(Spliterator.OfDouble spliterator, StreamContext context) { super(spliterator, context); }
final DoubleStreamEx delegate(Spliterator.OfDouble spliterator) { return new DoubleStreamEx(spliterator, context); }
@Override public OfDouble iterator() { return Spliterators.iterator(spliterator()); }
@Test public void testBasics() { assertFalse(DoubleStreamEx.of(1).isParallel()); assertTrue(DoubleStreamEx.of(1).parallel().isParallel()); assertFalse(DoubleStreamEx.of(1).parallel().sequential().isParallel()); AtomicInteger i = new AtomicInteger(); try (DoubleStreamEx s = DoubleStreamEx.of(1).onClose(i::incrementAndGet)) { assertEquals(1, s.count()); } assertEquals(1, i.get()); assertEquals(6, IntStreamEx.range(0, 4).asDoubleStream().sum(), 0); assertEquals(3, IntStreamEx.range(0, 4).asDoubleStream().max().getAsDouble(), 0); assertEquals(0, IntStreamEx.range(0, 4).asDoubleStream().min().getAsDouble(), 0); assertEquals(1.5, IntStreamEx.range(0, 4).asDoubleStream().average().getAsDouble(), 0.000001); assertEquals(4, IntStreamEx.range(0, 4).asDoubleStream().summaryStatistics().getCount()); assertArrayEquals(new double[] { 1, 2, 3 }, IntStreamEx.range(0, 5).asDoubleStream().skip(1).limit(3).toArray(), 0.0); assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(3, 1, 2).sorted().toArray(), 0.0); assertArrayEquals(new double[] { 1, 2, 3 }, DoubleStreamEx.of(1, 2, 1, 3, 2).distinct().toArray(), 0.0); assertArrayEquals(new int[] { 2, 4, 6 }, IntStreamEx.range(1, 4).asDoubleStream().mapToInt(x -> (int) x * 2) .toArray()); assertArrayEquals(new long[] { 2, 4, 6 }, IntStreamEx.range(1, 4).asDoubleStream().mapToLong(x -> (long) x * 2) .toArray()); assertArrayEquals(new double[] { 2, 4, 6 }, IntStreamEx.range(1, 4).asDoubleStream().map(x -> x * 2).toArray(), 0.0); assertArrayEquals(new double[] { 1, 3 }, IntStreamEx.range(0, 5).asDoubleStream().filter(x -> x % 2 == 1) .toArray(), 0.0); assertEquals(6.0, DoubleStreamEx.of(1.0, 2.0, 3.0).reduce(Double::sum).getAsDouble(), 0.0); assertEquals(Long.MAX_VALUE, LongStreamEx.rangeClosed(1, Long.MAX_VALUE).asDoubleStream().spliterator() .getExactSizeIfKnown()); assertArrayEquals(new double[] { 4, 2, 0, -2, -4 }, DoubleStreamEx.zip(new double[] { 5, 4, 3, 2, 1 }, new double[] { 1, 2, 3, 4, 5 }, (a, b) -> a - b).toArray(), 0.0); assertEquals("1.0; 0.5; 0.25; 0.125", DoubleStreamEx.of(1.0, 0.5, 0.25, 0.125).mapToObj(String::valueOf) .joining("; ")); List<Double> list = new ArrayList<>(); DoubleStreamEx.of(1.0, 0.5, 0.25, 0.125).forEach(list::add); assertEquals(Arrays.asList(1.0, 0.5, 0.25, 0.125), list); list = new ArrayList<>(); DoubleStreamEx.of(1.0, 0.5, 0.25, 0.125).parallel().forEachOrdered(list::add); assertEquals(Arrays.asList(1.0, 0.5, 0.25, 0.125), list); assertFalse(DoubleStreamEx.of(1.0, 2.0, 2.5).anyMatch(x -> x < 0.0)); assertTrue(DoubleStreamEx.of(1.0, 2.0, 2.5).anyMatch(x -> x >= 2.5)); assertTrue(DoubleStreamEx.of(1.0, 2.0, 2.5).noneMatch(x -> x < 0.0)); assertFalse(DoubleStreamEx.of(1.0, 2.0, 2.5).noneMatch(x -> x >= 2.5)); assertEquals(5.0, DoubleStreamEx.of(1.0, 2.0, 2.5).reduce(1, (a, b) -> a * b), 0.0); assertTrue(DoubleStreamEx.of(1, 2, 3).spliterator().hasCharacteristics(Spliterator.ORDERED)); assertFalse(DoubleStreamEx.of(1, 2, 3).unordered().spliterator().hasCharacteristics(Spliterator.ORDERED)); OfDouble iterator = DoubleStreamEx.of(1.0, 2.0, 3.0).iterator(); assertEquals(1.0, iterator.next(), 0.0); assertEquals(2.0, iterator.next(), 0.0); assertEquals(3.0, iterator.next(), 0.0); assertFalse(iterator.hasNext()); }
@Override public OfDouble iterator() { return ThrowingBridge.of(getDelegate().iterator(), getExceptionClass()); }
@Override public Spliterator.OfDouble spliterator() { return ThrowingBridge.of(getDelegate().spliterator(), getExceptionClass()); }
/** * Produces an array containing cumulative results of applying the * accumulation function going left to right. * * <p> * This is a terminal operation. * * <p> * For parallel stream it's not guaranteed that accumulator will always be * executed in the same thread. * * <p> * This method cannot take all the advantages of parallel streams as it must * process elements strictly left to right. * * @param accumulator a * <a href="package-summary.html#NonInterference">non-interfering * </a>, <a href="package-summary.html#Statelessness">stateless</a> * function for incorporating an additional element into a result * @return the array where the first element is the first element of this * stream and every successor element is the result of applying * accumulator function to the previous array element and the * corresponding stream element. The resulting array has the same * length as this stream. * @see #foldLeft(DoubleBinaryOperator) * @since 0.5.1 */ public double[] scanLeft(DoubleBinaryOperator accumulator) { Spliterator.OfDouble spliterator = spliterator(); double size = spliterator.getExactSizeIfKnown(); DoubleBuffer buf = new DoubleBuffer(size >= 0 && size <= Integer.MAX_VALUE ? (int) size : INITIAL_SIZE); delegate(spliterator).forEachOrdered(i -> buf.add(buf.size == 0 ? i : accumulator.applyAsDouble(buf.data[buf.size - 1], i))); return buf.toArray(); }
/** * Creates a <strong>parallel</strong> {@code double} stream from the given Spliterator. This operation is similar to * calling {@code StreamSupport.doubleStream(spliterator, true)} with the difference that a parallel * <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps">terminal * operation</a> will be executed in the given {@link ForkJoinPool}. * * @param spliterator A {@code Spliterator.OfDouble} describing the stream elements. Must not be {@code null}. * @param workerPool Thread pool for parallel execution of a terminal operation. Must not be {@code null}. * @return A parallel {@code double} stream that executes a terminal operation in the given {@link ForkJoinPool}. * @see StreamSupport#doubleStream(Spliterator.OfDouble, boolean) */ public static DoubleStream parallelStream(Spliterator.OfDouble spliterator, ForkJoinPool workerPool) { requireNonNull(spliterator, "Spliterator must not be null"); return new ParallelDoubleStreamSupport(doubleStream(spliterator, true), workerPool); }
/** * Creates a <strong>parallel</strong> {@code double} stream from the given Spliterator supplier. This operation is * similar to calling {@code StreamSupport.doubleStream(supplier, characteristics, true)} with the difference that a * parallel * <a href="https://docs.oracle.com/javase/8/docs/api/java/util/stream/package-summary.html#StreamOps">terminal * operation</a> will be executed in the given {@link ForkJoinPool}. * * @param supplier A {@code Supplier} of a {@code Spliterator.OfDouble}. Must not be {@code null}. * @param characteristics Spliterator characteristics of the supplied {@code Spliterator}. The characteristics must * be equal to {@code supplier.get().characteristics()}, otherwise undefined behavior may occur when terminal * operation commences. * @param workerPool Thread pool for parallel execution of a terminal operation. Must not be {@code null}. * @return A parallel {@code double} stream that executes a terminal operation in the given {@link ForkJoinPool}. * @see StreamSupport#doubleStream(Supplier, int, boolean) */ public static DoubleStream parallelStream(Supplier<? extends Spliterator.OfDouble> supplier, int characteristics, ForkJoinPool workerPool) { requireNonNull(supplier, "Supplier must not be null"); return new ParallelDoubleStreamSupport(doubleStream(supplier, characteristics, true), workerPool); }
/** * Returns a stream consisting of the remaining elements of this stream * after discarding the first {@code n} elements of the stream. If this * stream contains fewer than {@code n} elements then an empty stream will * be returned. * * <p> * This is a stateful quasi-intermediate operation. Unlike * {@link #skip(long)} it skips the first elements even if the stream is * unordered. The main purpose of this method is to workaround the problem * of skipping the first elements from non-sized source with further * parallel processing and unordered terminal operation (such as * {@link #forEach(DoubleConsumer)}). This problem was fixed in OracleJDK * 8u60. * * <p> * Also it behaves much better with infinite streams processed in parallel. * For example, * {@code DoubleStreamEx.iterate(0.0, i->i+1).skip(1).limit(100).parallel().toArray()} * will likely to fail with {@code OutOfMemoryError}, but will work nicely * if {@code skip} is replaced with {@code skipOrdered}. * * <p> * For sequential streams this method behaves exactly like * {@link #skip(long)}. * * @param n the number of leading elements to skip * @return the new stream * @throws IllegalArgumentException if {@code n} is negative * @see #skip(long) * @since 0.3.2 */ public DoubleStreamEx skipOrdered(long n) { Spliterator.OfDouble spliterator = (isParallel() ? StreamSupport.doubleStream(spliterator(), false) : stream()) .skip(n).spliterator(); return delegate(spliterator); }
/** * Returns a stream containing cumulative results of applying the * accumulation function going left to right. * * <p> * This is a stateful * <a href="package-summary.html#StreamOps">quasi-intermediate</a> * operation. * * <p> * This operation resembles {@link #scanLeft(DoubleBinaryOperator)}, but * unlike {@code scanLeft} this operation is intermediate and accumulation * function must be associative. * * <p> * This method cannot take all the advantages of parallel streams as it must * process elements strictly left to right. Using an unordered source or * removing the ordering constraint with {@link #unordered()} may improve * the parallel processing speed. * * @param op an <a href="package-summary.html#Associativity">associative</a> * , <a href="package-summary.html#NonInterference">non-interfering * </a>, <a href="package-summary.html#Statelessness">stateless</a> * function for computing the next element based on the previous one * @return the new stream. * @see #scanLeft(DoubleBinaryOperator) * @since 0.6.1 */ public DoubleStreamEx prefix(DoubleBinaryOperator op) { return delegate(new PrefixOps.OfDouble(spliterator(), op)); }
/** * Returns a sequential {@code DoubleStreamEx} containing a single element. * * @param element the single element * @return a singleton sequential stream */ public static DoubleStreamEx of(double element) { return of(new ConstSpliterator.OfDouble(element, 1, true)); }
/** * Returns a sequential {@link DoubleStreamEx} created from given * {@link java.util.Spliterator.OfDouble}. * * @param spliterator a spliterator to create the stream from. * @return the new stream * @since 0.3.4 */ public static DoubleStreamEx of(Spliterator.OfDouble spliterator) { return new DoubleStreamEx(spliterator, StreamContext.SEQUENTIAL); }
/** * Returns a sequential, ordered {@link DoubleStreamEx} created from given * {@link java.util.PrimitiveIterator.OfDouble}. * * <p> * This method is roughly equivalent to * {@code DoubleStreamEx.of(Spliterators.spliteratorUnknownSize(iterator, ORDERED))} * , but may show better performance for parallel processing. * * <p> * Use this method only if you cannot provide better Stream source. * * @param iterator an iterator to create the stream from. * @return the new stream * @since 0.5.1 */ public static DoubleStreamEx of(PrimitiveIterator.OfDouble iterator) { return of(new UnknownSizeSpliterator.USOfDouble(iterator)); }
/** * Returns a sequential unordered {@code DoubleStreamEx} of given length * which elements are equal to supplied value. * * @param value the constant value * @param length the length of the stream * @return a new {@code DoubleStreamEx} * @since 0.1.2 */ public static DoubleStreamEx constant(double value, long length) { return of(new ConstSpliterator.OfDouble(value, length, false)); }
/** * Returns the spliterator which covers all the elements emitted by this * emitter. * * @return the new spliterator */ default Spliterator.OfDouble spliterator() { return new EmitterSpliterator.OfDouble(this); }