java.util.Spliterator Java Examples

The following examples show how to use java.util.Spliterator. 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: DoubleStream.java    From TencentKona-8 with GNU General Public License v2.0 6 votes vote down vote up
/**
 * Returns an infinite sequential ordered {@code DoubleStream} produced by iterative
 * application of a function {@code f} to an initial element {@code seed},
 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
 * {@code f(f(seed))}, etc.
 *
 * <p>The first element (position {@code 0}) in the {@code DoubleStream}
 * will be the provided {@code seed}.  For {@code n > 0}, the element at
 * position {@code n}, will be the result of applying the function {@code f}
 *  to the element at position {@code n - 1}.
 *
 * @param seed the initial element
 * @param f a function to be applied to the previous element to produce
 *          a new element
 * @return a new sequential {@code DoubleStream}
 */
public static DoubleStream iterate(final double seed, final DoubleUnaryOperator f) {
    Objects.requireNonNull(f);
    final PrimitiveIterator.OfDouble iterator = new PrimitiveIterator.OfDouble() {
        double t = seed;

        @Override
        public boolean hasNext() {
            return true;
        }

        @Override
        public double nextDouble() {
            double v = t;
            t = f.applyAsDouble(t);
            return v;
        }
    };
    return StreamSupport.doubleStream(Spliterators.spliteratorUnknownSize(
            iterator,
            Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL), false);
}
 
Example #2
Source File: ConcurrentSkipListMap.java    From openjdk-jdk8u with GNU General Public License v2.0 6 votes vote down vote up
public Spliterator<K> trySplit() {
    Node<K,V> e; K ek;
    Comparator<? super K> cmp = comparator;
    K f = fence;
    if ((e = current) != null && (ek = e.key) != null) {
        for (Index<K,V> q = row; q != null; q = row = q.down) {
            Index<K,V> s; Node<K,V> b, n; K sk;
            if ((s = q.right) != null && (b = s.node) != null &&
                (n = b.next) != null && n.value != null &&
                (sk = n.key) != null && cpr(cmp, sk, ek) > 0 &&
                (f == null || cpr(cmp, sk, f) < 0)) {
                current = n;
                Index<K,V> r = q.down;
                row = (s.right != null) ? s : s.down;
                est -= est >>> 2;
                return new KeySpliterator<K,V>(cmp, r, e, sk, est);
            }
        }
    }
    return null;
}
 
Example #3
Source File: Generator.java    From java-coroutines with BSD 2-Clause "Simplified" License 6 votes vote down vote up
public static <T> Stream<T> stream(SuspendableConsumer<Generator<T>> runnable) {
	Generator<T> g = new Generator<T>();
	Coroutine c = new Coroutine(new SuspendableRunnable() {
		@Override
		public void run() throws SuspendExecution {
			runnable.apply(g);
		}
	});
	return StreamSupport.stream(Spliterators.spliteratorUnknownSize(new Iterator() {
		@Override
		public boolean hasNext() {
			return !c.isFinished();
		}

		@Override
		public Object next() {
			c.process();
			if (c.isFinished())
				return END;
			return g.value;
		}
	}, Spliterator.ORDERED), false).filter(v -> v != END);
}
 
Example #4
Source File: IntStream.java    From Bytecoder with Apache License 2.0 6 votes vote down vote up
/**
 * Returns an infinite sequential ordered {@code IntStream} produced by iterative
 * application of a function {@code f} to an initial element {@code seed},
 * producing a {@code Stream} consisting of {@code seed}, {@code f(seed)},
 * {@code f(f(seed))}, etc.
 *
 * <p>The first element (position {@code 0}) in the {@code IntStream} will be
 * the provided {@code seed}.  For {@code n > 0}, the element at position
 * {@code n}, will be the result of applying the function {@code f} to the
 * element at position {@code n - 1}.
 *
 * <p>The action of applying {@code f} for one element
 * <a href="../concurrent/package-summary.html#MemoryVisibility"><i>happens-before</i></a>
 * the action of applying {@code f} for subsequent elements.  For any given
 * element the action may be performed in whatever thread the library
 * chooses.
 *
 * @param seed the initial element
 * @param f a function to be applied to the previous element to produce
 *          a new element
 * @return a new sequential {@code IntStream}
 */
public static IntStream iterate(final int seed, final IntUnaryOperator f) {
    Objects.requireNonNull(f);
    Spliterator.OfInt spliterator = new Spliterators.AbstractIntSpliterator(Long.MAX_VALUE,
           Spliterator.ORDERED | Spliterator.IMMUTABLE | Spliterator.NONNULL) {
        int prev;
        boolean started;

        @Override
        public boolean tryAdvance(IntConsumer action) {
            Objects.requireNonNull(action);
            int t;
            if (started)
                t = f.applyAsInt(prev);
            else {
                t = seed;
                started = true;
            }
            action.accept(prev = t);
            return true;
        }
    };
    return StreamSupport.intStream(spliterator, false);
}
 
Example #5
Source File: ConcatTest.java    From dragonwell8_jdk with GNU General Public License v2.0 6 votes vote down vote up
private <T> void assertConcatContent(Spliterator<T> sp, boolean ordered, Spliterator<T> expected) {
    // concat stream cannot guarantee uniqueness
    assertFalse(sp.hasCharacteristics(Spliterator.DISTINCT), scenario);
    // concat stream cannot guarantee sorted
    assertFalse(sp.hasCharacteristics(Spliterator.SORTED), scenario);
    // concat stream is ordered if both are ordered
    assertEquals(sp.hasCharacteristics(Spliterator.ORDERED), ordered, scenario);

    // Verify elements
    if (ordered) {
        assertEquals(toBoxedList(sp),
                     toBoxedList(expected),
                     scenario);
    } else {
        assertEquals(toBoxedMultiset(sp),
                     toBoxedMultiset(expected),
                     scenario);
    }
}
 
Example #6
Source File: SpliteratorCollisions.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
private static <T, S extends Spliterator<T>> void testSplitUntilNull(
        Collection<T> exp,
        Supplier<S> supplier,
        UnaryOperator<Consumer<T>> boxingAdapter) {
    Spliterator<T> s = supplier.get();
    boolean isOrdered = s.hasCharacteristics(Spliterator.ORDERED);
    assertSpliterator(s);

    List<T> splits = new ArrayList<>();
    Consumer<T> c = boxingAdapter.apply(splits::add);

    testSplitUntilNull(new SplitNode<T>(c, s));
    assertContents(splits, exp, isOrdered);
}
 
Example #7
Source File: SliceOps.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
SliceTask(SliceTask<P_IN, P_OUT> parent, Spliterator<P_IN> spliterator) {
    super(parent, spliterator);
    this.op = parent.op;
    this.generator = parent.generator;
    this.targetOffset = parent.targetOffset;
    this.targetSize = parent.targetSize;
}
 
Example #8
Source File: SpliteratorLateBindingFailFastTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Test(dataProvider = "Source")
public <T> void lateBindingTestWithCharacteritics(String description, Supplier<Source<T>> ss) {
    Source<T> source = ss.get();
    Collection<T> c = source.asCollection();
    Spliterator<T> s = c.spliterator();
    s.characteristics();

    Set<T> r = new HashSet<>();
    s.forEachRemaining(r::add);

    assertEquals(r, new HashSet<>(c));
}
 
Example #9
Source File: CollectorOps.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
@Override
public <P_IN> Node<T> opEvaluateParallel(PipelineHelper<T> helper,
                                         Spliterator<P_IN> spliterator,
                                         IntFunction<T[]> generator) {
    int flags = helper.getStreamAndOpFlags();

    Assert.assertTrue(StreamOpFlag.SIZED.isKnown(flags));
    return super.opEvaluateParallel(helper, spliterator, generator);
}
 
Example #10
Source File: SliceOps.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
SliceTask(AbstractPipeline<P_OUT, P_OUT, ?> op,
          PipelineHelper<P_OUT> helper,
          Spliterator<P_IN> spliterator,
          IntFunction<P_OUT[]> generator,
          long offset, long size) {
    super(helper, spliterator);
    this.op = op;
    this.generator = generator;
    this.targetOffset = offset;
    this.targetSize = size;
}
 
Example #11
Source File: TestData.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
protected LongTestData(String name,
                       I state,
                       Function<I, LongStream> streamFn,
                       Function<I, LongStream> parStreamFn,
                       Function<I, Spliterator.OfLong> splitrFn,
                       ToIntFunction<I> sizeFn) {
    super(name, StreamShape.LONG_VALUE, state, streamFn, parStreamFn, splitrFn, sizeFn);
}
 
Example #12
Source File: SliceOps.java    From desugar_jdk_libs with GNU General Public License v2.0 5 votes vote down vote up
SliceTask(AbstractPipeline<P_OUT, P_OUT, ?> op,
          PipelineHelper<P_OUT> helper,
          Spliterator<P_IN> spliterator,
          IntFunction<P_OUT[]> generator,
          long offset, long size) {
    super(helper, spliterator);
    this.op = op;
    this.generator = generator;
    this.targetOffset = offset;
    this.targetSize = size;
}
 
Example #13
Source File: StreamSpliteratorTest.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
public Spliterator.OfInt trySplit() {
    splits++;
    Spliterator.OfInt prefix = psp.trySplit();
    if (prefix != null)
        prefixSplits++;
    return prefix;
}
 
Example #14
Source File: LinkedBlockingQueue.java    From openjdk-jdk8u with GNU General Public License v2.0 5 votes vote down vote up
public Spliterator<E> trySplit() {
    Node<E> h;
    final LinkedBlockingQueue<E> q = this.queue;
    int b = batch;
    int n = (b <= 0) ? 1 : (b >= MAX_BATCH) ? MAX_BATCH : b + 1;
    if (!exhausted &&
        ((h = current) != null || (h = q.head.next) != null) &&
        h.next != null) {
        Object[] a = new Object[n];
        int i = 0;
        Node<E> p = current;
        q.fullyLock();
        try {
            if (p != null || (p = q.head.next) != null) {
                do {
                    if ((a[i] = p.item) != null)
                        ++i;
                } while ((p = p.next) != null && i < n);
            }
        } finally {
            q.fullyUnlock();
        }
        if ((current = p) == null) {
            est = 0L;
            exhausted = true;
        }
        else if ((est -= i) < 0L)
            est = 0L;
        if (i > 0) {
            batch = i;
            return Spliterators.spliterator
                (a, 0, i, Spliterator.ORDERED | Spliterator.NONNULL |
                 Spliterator.CONCURRENT);
        }
    }
    return null;
}
 
Example #15
Source File: SpliteratorCharacteristics.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
void assertSortedMapCharacteristics(SortedMap<Integer, String> m, int keyCharacteristics) {
    assertMapCharacteristics(m, keyCharacteristics, Spliterator.SORTED);

    Set<Integer> keys = m.keySet();
    if (m.comparator() != null) {
        assertNotNullComparator(keys);
    }
    else {
        assertNullComparator(keys);
    }

    assertISEComparator(m.values());

    assertNotNullComparator(m.entrySet());
}
 
Example #16
Source File: DoublePipeline.java    From JDKSourceCode1.8 with MIT License 5 votes vote down vote up
@Override
final <P_IN> Node<Double> evaluateToNode(PipelineHelper<Double> helper,
                                         Spliterator<P_IN> spliterator,
                                         boolean flattenTree,
                                         IntFunction<Double[]> generator) {
    return Nodes.collectDouble(helper, spliterator, flattenTree);
}
 
Example #17
Source File: OpTestCase.java    From dragonwell8_jdk with GNU General Public License v2.0 5 votes vote down vote up
AbstractPipeline createPipeline(StreamShape shape, Spliterator s, int flags, boolean parallel) {
    switch (shape) {
        case REFERENCE:    return new ReferencePipeline.Head<>(s, flags, parallel);
        case INT_VALUE:    return new IntPipeline.Head(s, flags, parallel);
        case LONG_VALUE:   return new LongPipeline.Head(s, flags, parallel);
        case DOUBLE_VALUE: return new DoublePipeline.Head(s, flags, parallel);
        default: throw new IllegalStateException("Unknown shape: " + shape);
    }
}
 
Example #18
Source File: CharSequence.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Returns a stream of {@code int} zero-extending the {@code char} values
 * from this sequence.  Any char which maps to a <a
 * href="{@docRoot}/java/lang/Character.html#unicode">surrogate code
 * point</a> is passed through uninterpreted.
 *
 * <p>If the sequence is mutated while the stream is being read, the
 * result is undefined.
 *
 * @return an IntStream of char values from this sequence
 * @since 1.8
 */
public default IntStream chars() {
    class CharIterator implements PrimitiveIterator.OfInt {
        int cur = 0;

        public boolean hasNext() {
            return cur < length();
        }

        public int nextInt() {
            if (hasNext()) {
                return charAt(cur++);
            } else {
                throw new NoSuchElementException();
            }
        }

        @Override
        public void forEachRemaining(IntConsumer block) {
            for (; cur < length(); cur++) {
                block.accept(charAt(cur));
            }
        }
    }

    return StreamSupport.intStream(() ->
            Spliterators.spliterator(
                    new CharIterator(),
                    length(),
                    Spliterator.ORDERED),
            Spliterator.SUBSIZED | Spliterator.SIZED | Spliterator.ORDERED,
            false);
}
 
Example #19
Source File: TestData.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
public static OfDouble ofNode(String name, Node.OfDouble node) {
    int characteristics = Spliterator.SIZED | Spliterator.ORDERED;
    return new AbstractTestData.DoubleTestData<>(name, node,
                                                 n -> StreamSupport.doubleStream(n::spliterator, characteristics, false),
                                                 n -> StreamSupport.doubleStream(n::spliterator, characteristics, true),
                                                 Node.OfDouble::spliterator,
                                                 n -> (int) n.count());
}
 
Example #20
Source File: DoublePipeline.java    From jdk1.8-source-analysis with Apache License 2.0 5 votes vote down vote up
/**
 * Adapt a {@code Spliterator<Double>} to a {@code Spliterator.OfDouble}.
 *
 * @implNote
 * The implementation attempts to cast to a Spliterator.OfDouble, and throws
 * an exception if this cast is not possible.
 */
private static Spliterator.OfDouble adapt(Spliterator<Double> s) {
    if (s instanceof Spliterator.OfDouble) {
        return (Spliterator.OfDouble) s;
    } else {
        if (Tripwire.ENABLED)
            Tripwire.trip(AbstractPipeline.class,
                          "using DoubleStream.adapt(Spliterator<Double> s)");
        throw new UnsupportedOperationException("DoubleStream.adapt(Spliterator<Double> s)");
    }
}
 
Example #21
Source File: Test73.java    From blog with BSD 2-Clause "Simplified" License 5 votes vote down vote up
public static void main(String[] args) {
	final String SENTENCE = " Nel mezzo del cammin di nostra vita " + "mi ritrovai in una selva oscura"
			+ " ché la dritta via era smarrita ";
	System.out.println("Found " + countWordsIteratively(SENTENCE) + " words");

	Stream<Character> stream = IntStream.range(0, SENTENCE.length()).mapToObj(SENTENCE::charAt);
	System.out.println("Found " + countWords(stream) + " words");
	
	
	Spliterator<Character> spliterator = new WordCounterSpliterator(SENTENCE);
	Stream<Character> stream2 = StreamSupport.stream(spliterator, true);
	System.out.println("Found " + countWords(stream2) + " words");
}
 
Example #22
Source File: StringUTF16.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
CharsSpliterator(byte[] array, int origin, int fence, int acs) {
    this.array = array;
    this.index = origin;
    this.fence = fence;
    this.cs = acs | Spliterator.ORDERED | Spliterator.SIZED
              | Spliterator.SUBSIZED;
}
 
Example #23
Source File: ForEachOps.java    From desugar_jdk_libs with GNU General Public License v2.0 5 votes vote down vote up
protected ForEachOrderedTask(PipelineHelper<T> helper,
                             Spliterator<S> spliterator,
                             Sink<T> action) {
    super(null);
    this.helper = helper;
    this.spliterator = spliterator;
    this.targetSize = AbstractTask.suggestTargetSize(spliterator.estimateSize());
    // Size map to avoid concurrent re-sizes
    this.completionMap = new ConcurrentHashMap<>(Math.max(16, AbstractTask.LEAF_TARGET << 1));
    this.action = action;
    this.leftPredecessor = null;
}
 
Example #24
Source File: AbstractPipeline.java    From jdk8u-jdk with GNU General Public License v2.0 5 votes vote down vote up
@Override
@SuppressWarnings("unchecked")
final <P_IN> Spliterator<E_OUT> wrapSpliterator(Spliterator<P_IN> sourceSpliterator) {
    if (depth == 0) {
        return (Spliterator<E_OUT>) sourceSpliterator;
    }
    else {
        return wrap(this, () -> sourceSpliterator, isParallel());
    }
}
 
Example #25
Source File: Lines.java    From TencentKona-8 with GNU General Public License v2.0 5 votes vote down vote up
public void testCharacteristics() {
    try (BufferedReader br = new BufferedReader(
                                new StringReader(""))) {
        Spliterator<String> instance = br.lines().spliterator();
        assertTrue(instance.hasCharacteristics(Spliterator.NONNULL));
        assertTrue(instance.hasCharacteristics(Spliterator.ORDERED));
    } catch (IOException ioe) {
        fail("Should not have any exception.");
    }
}
 
Example #26
Source File: ForEachOps.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
ForEachTask(ForEachTask<S, T> parent, Spliterator<S> spliterator) {
    super(parent);
    this.spliterator = spliterator;
    this.sink = parent.sink;
    this.targetSize = parent.targetSize;
    this.helper = parent.helper;
}
 
Example #27
Source File: ConcurrentHashMap.java    From desugar_jdk_libs with GNU General Public License v2.0 5 votes vote down vote up
public Spliterator<K> spliterator() {
    Node<K,V>[] t;
    ConcurrentHashMap<K,V> m = map;
    long n = m.sumCount();
    int f = (t = m.table) == null ? 0 : t.length;
    return new KeySpliterator<K,V>(t, f, 0, f, n < 0L ? 0L : n);
}
 
Example #28
Source File: SpliteratorLateBindingFailFastHelper.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
public IntSource(T b, Function<? super T, Spliterator.OfInt> toSpliterator,
                 Consumer<T> updater) {
    this(b, toSpliterator, updater, false);
}
 
Example #29
Source File: SpliteratorCharacteristics.java    From jdk8u-jdk with GNU General Public License v2.0 4 votes vote down vote up
public void testConcurrentSkipListSet() {
    assertSortedSetCharacteristics(new ConcurrentSkipListSet<>(),
                                   Spliterator.CONCURRENT | Spliterator.NONNULL |
                                   Spliterator.DISTINCT | Spliterator.SORTED |
                                   Spliterator.ORDERED);
}
 
Example #30
Source File: LinkedBlockingDeque.java    From jdk8u60 with GNU General Public License v2.0 4 votes vote down vote up
public int characteristics() {
    return Spliterator.ORDERED | Spliterator.NONNULL |
        Spliterator.CONCURRENT;
}