Java Code Examples for java.util.Spliterators#spliteratorUnknownSize()

The following examples show how to use java.util.Spliterators#spliteratorUnknownSize() . 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: SpliteratorsTest.java    From j2objc with Apache License 2.0 6 votes vote down vote up
public void testSpliterator_unsizedIterator() {
    String[] array = { "a", "b", "c", "d", "e", "f", "g", "h" };
    List<String> asList = Arrays.asList(array);
    ArrayList<String> expectedValues = new ArrayList<>(asList);

    Spliterator<String> sp = Spliterators.spliteratorUnknownSize(asList.iterator(), 0);
    SpliteratorTester.runBasicIterationTests(sp, expectedValues);

    sp = Spliterators.spliteratorUnknownSize(asList.iterator(), 0);
    SpliteratorTester.testSpliteratorNPE(sp);

    sp = Spliterators.spliteratorUnknownSize(asList.iterator(), 0);
    SpliteratorTester.runBasicSplitTests(sp, expectedValues, String::compareTo);

    // Assert the spliterator inherits any characteristics we ask it to.
    sp = Spliterators.spliterator(array, Spliterator.ORDERED);
    assertTrue(sp.hasCharacteristics(Spliterator.ORDERED));
}
 
Example 2
Source File: ZipSpliteratorTest.java    From streamex with Apache License 2.0 5 votes vote down vote up
@Test
public void testUnknownSize() {
    List<String> expected = IntStreamEx.range(200).mapToObj(x -> x + ":" + (x + 1)).toList();
    Supplier<Spliterator<String>> s = () -> new ZipSpliterator<>(Spliterators.spliteratorUnknownSize(IntStreamEx
            .range(200).iterator(), Spliterator.ORDERED), Spliterators.spliteratorUnknownSize(IntStreamEx.range(1,
        201).iterator(), Spliterator.ORDERED), (x, y) -> x + ":" + y, true);
    checkSpliterator("unknownSize", expected, s);
}
 
Example 3
Source File: JsonInputIterator.java    From selenium with Apache License 2.0 5 votes vote down vote up
public Stream<JsonInput> asStream() {
  Spliterator<JsonInput> spliterator = Spliterators.spliteratorUnknownSize(
      this,
      ORDERED & IMMUTABLE);

  return StreamSupport.stream(spliterator, false);
}
 
Example 4
Source File: ToSpliterator.java    From linq with Apache License 2.0 5 votes vote down vote up
public static <TSource> Spliterator<TSource> spliterator(IEnumerable<TSource> source) {
    if (source == null)
        ThrowHelper.throwArgumentNullException(ExceptionArgument.source);

    if (source instanceof ICollection) {
        if (source instanceof IArray) {
            IArray<TSource> array = (IArray<TSource>) source;
            Object arr = array.getArray();
            Class<?> componentType = arr.getClass().getComponentType();
            if (componentType.isPrimitive()) {
                if (componentType == int.class)
                    //noinspection unchecked
                    return (Spliterator<TSource>) Spliterators.spliterator((int[]) arr, array._getStartIndex(), array._getEndIndex(), Spliterator.IMMUTABLE);
                if (componentType == long.class)
                    //noinspection unchecked
                    return (Spliterator<TSource>) Spliterators.spliterator((long[]) arr, array._getStartIndex(), array._getEndIndex(), Spliterator.IMMUTABLE);
                if (componentType == double.class)
                    //noinspection unchecked
                    return (Spliterator<TSource>) Spliterators.spliterator((double[]) arr, array._getStartIndex(), array._getEndIndex(), Spliterator.IMMUTABLE);
                return Spliterators.spliterator(array._toArray(), array._getStartIndex(), array._getEndIndex(), Spliterator.IMMUTABLE);
            }
            return Spliterators.spliterator((Object[]) arr, array._getStartIndex(), array._getEndIndex(), Spliterator.IMMUTABLE);
        }

        ICollection<TSource> collection = (ICollection<TSource>) source;
        return Spliterators.spliterator(collection.getCollection(), Spliterator.IMMUTABLE);
    }

    if (source instanceof IIListProvider) {
        IIListProvider<TSource> listProv = (IIListProvider<TSource>) source;
        int count = listProv._getCount(true);
        if (count != -1)
            return Spliterators.spliterator(source.enumerator(), count, Spliterator.IMMUTABLE);
    }

    return Spliterators.spliteratorUnknownSize(source.enumerator(), Spliterator.IMMUTABLE);
}
 
Example 5
Source File: ObservableSensor.java    From htm.java with GNU Affero General Public License v3.0 5 votes vote down vote up
/**
 * Creates a new {@code ObservableSensor} using the specified 
 * {@link SensorParams}
 * 
 * @param params
 */
@SuppressWarnings("unchecked")
public ObservableSensor(SensorParams params) {
    if(!params.hasKey("ONSUB")) {
        throw new IllegalArgumentException("Passed improperly formed Tuple: no key for \"ONSUB\"");
    }
    
    this.params = params;
    
    Observable<String> obs = null;
    Object publisher = params.get("ONSUB");
    if(publisher instanceof Publisher) {
        obs = ((Publisher)publisher).observable();
    } else if(publisher instanceof Supplier<?>) {
        obs = ((Supplier<Publisher>)publisher).get().observable();
    } else {
        obs = (Observable<String>)publisher; 
    }
    
    Iterator<String> observerator = obs.toBlocking().getIterator();
    
    Iterator<String> iterator = new Iterator<String>() {
        @Override public boolean hasNext() { return observerator.hasNext(); }
        @Override public String next() {
            return observerator.next();
        }
    };
            
    int characteristics = Spliterator.SORTED | Spliterator.ORDERED;
    Spliterator<String> spliterator = Spliterators.spliteratorUnknownSize(iterator, characteristics);
  
    this.stream = BatchedCsvStream.batch(
        StreamSupport.stream(spliterator, false), BATCH_SIZE, DEFAULT_PARALLEL_MODE, HEADER_SIZE);
}
 
Example 6
Source File: OpenCSVParser.java    From quick-csv-streamer with GNU General Public License v2.0 5 votes vote down vote up
public Stream<City> parse(InputStream is) {
    Reader reader = new InputStreamReader(is);
    CSVReader csvReader = new CSVReader(reader);
    Iterator<City> iterator = new Iterator<City>() {
        private boolean isEndReached = false;
        
        @Override
        public boolean hasNext() {
            return !isEndReached;
        }

        @Override
        public City next() {
            try {
                String[] values = csvReader.readNext();
                if (values == null) {
                    isEndReached = true;
                    return null;
                } else {
                    return toCity(values);
                }
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    };
    Spliterator<City> spliterator = Spliterators.spliteratorUnknownSize(iterator, Spliterator.ORDERED);
    return StreamSupport.stream(spliterator, false).onClose(new Runnable() {
        @Override
        public void run() {
            IOUtils.closeQuietly(csvReader);
        }
    });
}
 
Example 7
Source File: BlockingIterable.java    From reactive-streams-commons with Apache License 2.0 5 votes vote down vote up
/**
 * @return a {@link Stream} of unknown size with onClose attached to {@link Subscription#cancel()}
 */
public Stream<T> stream() {
    BlockingIterable.SubscriberIterator<T> it = createIterator();
    source.subscribe(it);

    Spliterator<T> sp = Spliterators.spliteratorUnknownSize(it, 0);

    return StreamSupport.stream(sp, false).onClose(it);
}
 
Example 8
Source File: BlockingIterable.java    From reactive-streams-commons with Apache License 2.0 5 votes vote down vote up
/**
 * @return a {@link Stream} of unknown size with onClose attached to {@link Subscription#cancel()}
 */
public Stream<T> parallelStream() {
    BlockingIterable.SubscriberIterator<T> it = createIterator();
    source.subscribe(it);

    Spliterator<T> sp = Spliterators.spliteratorUnknownSize(it, 0);

    return StreamSupport.stream(sp, true).onClose(it);
}
 
Example 9
Source File: SkippingIterator.java    From monsoon with BSD 3-Clause "New" or "Revised" License 5 votes vote down vote up
public static <T> Stream<T> adaptStream(Stream<T> stream, Function<? super T, ? extends DateTime> timestamp_fn, Duration stepsize) {
    if (stepsize.getMillis() <= 0L) return stream;

    final Iterator<T> iter = new SkippingIterator<>(stream.iterator(), timestamp_fn, stepsize);
    final Spliterator<T> spliter = Spliterators.spliteratorUnknownSize(iter, NONNULL | IMMUTABLE | ORDERED);
    return StreamSupport.stream(spliter, false);
}
 
Example 10
Source File: AbstractCollectionResource.java    From okta-sdk-java with Apache License 2.0 4 votes vote down vote up
@Override
public Spliterator<T> spliterator() {
    return Spliterators.spliteratorUnknownSize(iterator(), Spliterator.ORDERED);
}
 
Example 11
Source File: StreamTest.java    From util4j with Apache License 2.0 4 votes vote down vote up
public Spliterator<String> spliterator() {
    return Spliterators.spliteratorUnknownSize(list.iterator(), 0);
}
 
Example 12
Source File: Files.java    From openjdk-jdk9 with GNU General Public License v2.0 4 votes vote down vote up
/**
 * Return a {@code Stream} that is lazily populated with {@code
 * Path} by searching for files in a file tree rooted at a given starting
 * file.
 *
 * <p> This method walks the file tree in exactly the manner specified by
 * the {@link #walk walk} method. For each file encountered, the given
 * {@link BiPredicate} is invoked with its {@link Path} and {@link
 * BasicFileAttributes}. The {@code Path} object is obtained as if by
 * {@link Path#resolve(Path) resolving} the relative path against {@code
 * start} and is only included in the returned {@link Stream} if
 * the {@code BiPredicate} returns true. Compare to calling {@link
 * java.util.stream.Stream#filter filter} on the {@code Stream}
 * returned by {@code walk} method, this method may be more efficient by
 * avoiding redundant retrieval of the {@code BasicFileAttributes}.
 *
 * <p> The returned stream contains references to one or more open directories.
 * The directories are closed by closing the stream.
 *
 * <p> If an {@link IOException} is thrown when accessing the directory
 * after returned from this method, it is wrapped in an {@link
 * UncheckedIOException} which will be thrown from the method that caused
 * the access to take place.
 *
 * @apiNote
 * This method must be used within a try-with-resources statement or similar
 * control structure to ensure that the stream's open directories are closed
 * promptly after the stream's operations have completed.
 *
 * @param   start
 *          the starting file
 * @param   maxDepth
 *          the maximum number of directory levels to search
 * @param   matcher
 *          the function used to decide whether a file should be included
 *          in the returned stream
 * @param   options
 *          options to configure the traversal
 *
 * @return  the {@link Stream} of {@link Path}
 *
 * @throws  IllegalArgumentException
 *          if the {@code maxDepth} parameter is negative
 * @throws  SecurityException
 *          If the security manager denies access to the starting file.
 *          In the case of the default provider, the {@link
 *          SecurityManager#checkRead(String) checkRead} method is invoked
 *          to check read access to the directory.
 * @throws  IOException
 *          if an I/O error is thrown when accessing the starting file.
 *
 * @see     #walk(Path, int, FileVisitOption...)
 * @since   1.8
 */
public static Stream<Path> find(Path start,
                                int maxDepth,
                                BiPredicate<Path, BasicFileAttributes> matcher,
                                FileVisitOption... options)
    throws IOException
{
    FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);
    try {
        Spliterator<FileTreeWalker.Event> spliterator =
            Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT);
        return StreamSupport.stream(spliterator, false)
                            .onClose(iterator::close)
                            .filter(entry -> matcher.test(entry.file(), entry.attributes()))
                            .map(entry -> entry.file());
    } catch (Error|RuntimeException e) {
        iterator.close();
        throw e;
    }
}
 
Example 13
Source File: Files.java    From Bytecoder with Apache License 2.0 4 votes vote down vote up
/**
 * Return a {@code Stream} that is lazily populated with {@code
 * Path} by searching for files in a file tree rooted at a given starting
 * file.
 *
 * <p> This method walks the file tree in exactly the manner specified by
 * the {@link #walk walk} method. For each file encountered, the given
 * {@link BiPredicate} is invoked with its {@link Path} and {@link
 * BasicFileAttributes}. The {@code Path} object is obtained as if by
 * {@link Path#resolve(Path) resolving} the relative path against {@code
 * start} and is only included in the returned {@link Stream} if
 * the {@code BiPredicate} returns true. Compare to calling {@link
 * java.util.stream.Stream#filter filter} on the {@code Stream}
 * returned by {@code walk} method, this method may be more efficient by
 * avoiding redundant retrieval of the {@code BasicFileAttributes}.
 *
 * <p> The returned stream contains references to one or more open directories.
 * The directories are closed by closing the stream.
 *
 * <p> If an {@link IOException} is thrown when accessing the directory
 * after returned from this method, it is wrapped in an {@link
 * UncheckedIOException} which will be thrown from the method that caused
 * the access to take place.
 *
 * @apiNote
 * This method must be used within a try-with-resources statement or similar
 * control structure to ensure that the stream's open directories are closed
 * promptly after the stream's operations have completed.
 *
 * @param   start
 *          the starting file
 * @param   maxDepth
 *          the maximum number of directory levels to search
 * @param   matcher
 *          the function used to decide whether a file should be included
 *          in the returned stream
 * @param   options
 *          options to configure the traversal
 *
 * @return  the {@link Stream} of {@link Path}
 *
 * @throws  IllegalArgumentException
 *          if the {@code maxDepth} parameter is negative
 * @throws  SecurityException
 *          If the security manager denies access to the starting file.
 *          In the case of the default provider, the {@link
 *          SecurityManager#checkRead(String) checkRead} method is invoked
 *          to check read access to the directory.
 * @throws  IOException
 *          if an I/O error is thrown when accessing the starting file.
 *
 * @see     #walk(Path, int, FileVisitOption...)
 * @since   1.8
 */
public static Stream<Path> find(Path start,
                                int maxDepth,
                                BiPredicate<Path, BasicFileAttributes> matcher,
                                FileVisitOption... options)
    throws IOException
{
    FileTreeIterator iterator = new FileTreeIterator(start, maxDepth, options);
    try {
        Spliterator<FileTreeWalker.Event> spliterator =
            Spliterators.spliteratorUnknownSize(iterator, Spliterator.DISTINCT);
        return StreamSupport.stream(spliterator, false)
                            .onClose(iterator::close)
                            .filter(entry -> matcher.test(entry.file(), entry.attributes()))
                            .map(entry -> entry.file());
    } catch (Error|RuntimeException e) {
        iterator.close();
        throw e;
    }
}
 
Example 14
Source File: StackTraces.java    From es6draft with MIT License 3 votes vote down vote up
/**
 * Returns the script stack trace elements.
 * 
 * @param e
 *            the throwable object
 * @return the script stack trace elements
 */
public static Stream<StackTraceElement> stackTraceStream(Throwable e) {
    StackTraceElementIterator iterator = new StackTraceElementIterator(e);
    int characteristics = Spliterator.IMMUTABLE | Spliterator.NONNULL | Spliterator.ORDERED;
    Spliterator<StackTraceElement> spliterator = Spliterators.spliteratorUnknownSize(iterator, characteristics);
    return StreamSupport.stream(spliterator, false).map(StackTraces::toScriptFrame);
}
 
Example 15
Source File: Iterable.java    From openjdk-jdk9 with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Creates a {@link Spliterator} over the elements described by this
 * {@code Iterable}.
 *
 * @implSpec
 * The default implementation creates an
 * <em><a href="../util/Spliterator.html#binding">early-binding</a></em>
 * spliterator from the iterable's {@code Iterator}.  The spliterator
 * inherits the <em>fail-fast</em> properties of the iterable's iterator.
 *
 * @implNote
 * The default implementation should usually be overridden.  The
 * spliterator returned by the default implementation has poor splitting
 * capabilities, is unsized, and does not report any spliterator
 * characteristics. Implementing classes can nearly always provide a
 * better implementation.
 *
 * @return a {@code Spliterator} over the elements described by this
 * {@code Iterable}.
 * @since 1.8
 */
default Spliterator<T> spliterator() {
    return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
 
Example 16
Source File: Iterable.java    From Bytecoder with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a {@link Spliterator} over the elements described by this
 * {@code Iterable}.
 *
 * @implSpec
 * The default implementation creates an
 * <em><a href="../util/Spliterator.html#binding">early-binding</a></em>
 * spliterator from the iterable's {@code Iterator}.  The spliterator
 * inherits the <em>fail-fast</em> properties of the iterable's iterator.
 *
 * @implNote
 * The default implementation should usually be overridden.  The
 * spliterator returned by the default implementation has poor splitting
 * capabilities, is unsized, and does not report any spliterator
 * characteristics. Implementing classes can nearly always provide a
 * better implementation.
 *
 * @return a {@code Spliterator} over the elements described by this
 * {@code Iterable}.
 * @since 1.8
 */
default Spliterator<T> spliterator() {
    return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
 
Example 17
Source File: SetOfUnknownSize.java    From sis with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a {@code Spliterator} without knowledge of collection size.
 *
 * @return a {@code Spliterator} over the elements in this collection.
 */
@Override
public Spliterator<E> spliterator() {
    return isSizeKnown() ? super.spliterator() : Spliterators.spliteratorUnknownSize(iterator(), 0);
}
 
Example 18
Source File: ResultSet.java    From cqengine with Apache License 2.0 2 votes vote down vote up
/**
 * Creates a {@link Spliterator} over objects matching the query for which this {@link ResultSet} was constructed.
 *
 * @return a {@link Spliterator} over objects matching the query for which this {@link ResultSet} was constructed
 */
public Spliterator<O> spliterator() {
    return Spliterators.spliteratorUnknownSize(this.iterator(), Spliterator.ORDERED);
}
 
Example 19
Source File: Iterable.java    From JDKSourceCode1.8 with MIT License 2 votes vote down vote up
/**
 * Creates a {@link Spliterator} over the elements described by this
 * {@code Iterable}.
 *
 * @implSpec
 * The default implementation creates an
 * <em><a href="Spliterator.html#binding">early-binding</a></em>
 * spliterator from the iterable's {@code Iterator}.  The spliterator
 * inherits the <em>fail-fast</em> properties of the iterable's iterator.
 *
 * @implNote
 * The default implementation should usually be overridden.  The
 * spliterator returned by the default implementation has poor splitting
 * capabilities, is unsized, and does not report any spliterator
 * characteristics. Implementing classes can nearly always provide a
 * better implementation.
 *
 * @return a {@code Spliterator} over the elements described by this
 * {@code Iterable}.
 * @since 1.8
 */
default Spliterator<T> spliterator() {
    return Spliterators.spliteratorUnknownSize(iterator(), 0);
}
 
Example 20
Source File: Iterable.java    From openjdk-8-source with GNU General Public License v2.0 2 votes vote down vote up
/**
 * Creates a {@link Spliterator} over the elements described by this
 * {@code Iterable}.
 *
 * @implSpec
 * The default implementation creates an
 * <em><a href="Spliterator.html#binding">early-binding</a></em>
 * spliterator from the iterable's {@code Iterator}.  The spliterator
 * inherits the <em>fail-fast</em> properties of the iterable's iterator.
 *
 * @implNote
 * The default implementation should usually be overridden.  The
 * spliterator returned by the default implementation has poor splitting
 * capabilities, is unsized, and does not report any spliterator
 * characteristics. Implementing classes can nearly always provide a
 * better implementation.
 *
 * @return a {@code Spliterator} over the elements described by this
 * {@code Iterable}.
 * @since 1.8
 */
default Spliterator<T> spliterator() {
    return Spliterators.spliteratorUnknownSize(iterator(), 0);
}