下面列出了java.util.Spliterators#spliteratorUnknownSize ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。
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));
}
@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);
}
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);
}
/**
* @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);
}
/**
* @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);
}
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);
}
});
}
/**
* 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);
}
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);
}
public Stream<JsonInput> asStream() {
Spliterator<JsonInput> spliterator = Spliterators.spliteratorUnknownSize(
this,
ORDERED & IMMUTABLE);
return StreamSupport.stream(spliterator, false);
}
@Override
public Spliterator<T> spliterator() {
return Spliterators.spliteratorUnknownSize(iterator(), Spliterator.ORDERED);
}
public Spliterator<String> spliterator() {
return Spliterators.spliteratorUnknownSize(list.iterator(), 0);
}
/**
* 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;
}
}
/**
* 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;
}
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}
/**
* 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);
}