use of java8.util.Spliterator in project streamsupport by stefan-zobel.
the class Collection8Test method testRandomElementRemovalDuringTraversal.
/**
* Some elements randomly disappear in the middle of traversal.
*/
@SuppressWarnings({ "rawtypes", "unchecked" })
@Test(dataProvider = "Source")
public void testRandomElementRemovalDuringTraversal(String description, Supplier<CollectionImplementation> sci) {
CollectionImplementation impl = sci.get();
if (CopyOnWriteArrayList.class.equals(impl.klazz()) || CopyOnWriteArraySet.class.equals(impl.klazz())) {
return;
}
if (HAS_JAVA8_SPLITERATOR_BUG && (LinkedBlockingDeque.class.equals(impl.klazz())) || LinkedBlockingQueue.class.equals(impl.klazz())) {
// https://bugs.openjdk.java.net/browse/JDK-8171051
return;
}
Collection c = impl.emptyCollection();
ThreadLocalRandom rnd = ThreadLocalRandom.current();
int n = rnd.nextInt(6);
ArrayList copy = new ArrayList();
for (int i = 0; i < n; i++) {
Object x = impl.makeElement(i);
copy.add(x);
c.add(x);
}
ArrayList iterated = new ArrayList();
ArrayList spliterated = new ArrayList();
ArrayList removed = new ArrayList();
Spliterator<?> s = Spliterators.spliterator(c);
Iterator<?> it = c.iterator();
if (!(s.hasCharacteristics(Spliterator.CONCURRENT) || s.hasCharacteristics(Spliterator.IMMUTABLE)))
return;
for (int i = rnd.nextInt(n + 1); --i >= 0; ) {
assertTrue(s.tryAdvance(e -> {
}));
if (rnd.nextBoolean())
assertTrue(it.hasNext());
it.next();
}
// TODO: many more removal methods
if (rnd.nextBoolean()) {
for (Iterator<?> z = c.iterator(); z.hasNext(); ) {
Object e = z.next();
if (rnd.nextBoolean()) {
try {
z.remove();
} catch (UnsupportedOperationException ok) {
return;
}
removed.add(e);
}
}
} else {
Predicate randomlyRemove = e -> {
if (rnd.nextBoolean()) {
removed.add(e);
return true;
} else
return false;
};
Iterables.removeIf(c, randomlyRemove);
}
s.forEachRemaining(spliterated::add);
while (it.hasNext()) iterated.add(it.next());
assertTrue(copy.containsAll(iterated));
assertTrue(copy.containsAll(spliterated));
assertTrue(copy.containsAll(removed));
if (s.hasCharacteristics(Spliterator.CONCURRENT)) {
ArrayList<?> iteratedAndRemoved = new ArrayList<>(iterated);
ArrayList<?> spliteratedAndRemoved = new ArrayList<>(spliterated);
iteratedAndRemoved.retainAll(removed);
spliteratedAndRemoved.retainAll(removed);
assertTrue(iteratedAndRemoved.size() <= 1);
assertTrue(spliteratedAndRemoved.size() <= 1);
if (testImplementationDetails && !(c instanceof java.util.concurrent.ArrayBlockingQueue))
assertTrue(spliteratedAndRemoved.isEmpty());
}
}
use of java8.util.Spliterator in project streamsupport by stefan-zobel.
the class ConcatTest method assertLongConcat.
private void assertLongConcat(Stream<Integer> s1, Stream<Integer> s2, boolean parallel, boolean ordered) {
LongStream result = LongStreams.concat(s1.mapToLong(Integer::longValue), s2.mapToLong(Integer::longValue));
assertEquals(result.isParallel(), parallel);
assertConcatContent(result.spliterator(), ordered, StreamSupport.stream(expected).mapToLong(Integer::longValue).spliterator());
}
use of java8.util.Spliterator in project streamsupport by stefan-zobel.
the class SequentialOpTest method testLazy.
@SuppressWarnings("unchecked")
@Test(dataProvider = "StreamTestData<Integer>", dataProviderClass = StreamTestDataProvider.class, groups = { "serialization-hostile" })
public void testLazy(String name, TestData.OfRef<Integer> data) {
Function<Integer, Integer> id = LambdaTestHelpers.identity();
AtomicInteger counter = new AtomicInteger();
Supplier<Stream<Integer>>[] suppliers = new Supplier[] { () -> data.stream(), () -> data.parallelStream() };
UnaryOperator<Stream<Integer>>[] configs = new UnaryOperator[] { (UnaryOperator<Stream<Integer>>) s -> s.peek(e -> {
counter.incrementAndGet();
}), (UnaryOperator<Stream<Integer>>) s -> s.map(id).peek(e -> {
counter.incrementAndGet();
}).sequential().map(id), (UnaryOperator<Stream<Integer>>) s -> s.map(id).peek(e -> {
counter.incrementAndGet();
}).parallel().map(id), (UnaryOperator<Stream<Integer>>) s -> s.sequential().map(id).peek(e -> {
counter.incrementAndGet();
}).map(id), (UnaryOperator<Stream<Integer>>) s -> s.parallel().map(id).peek(e -> {
counter.incrementAndGet();
}).map(id) };
for (int i = 0; i < suppliers.length; i++) {
setContext("supplierIndex", i);
Supplier<Stream<Integer>> supp = suppliers[i];
for (int j = 0; j < configs.length; j++) {
setContext("configIndex", j);
UnaryOperator<Stream<Integer>> config = configs[j];
counter.set(0);
Stream<Integer> stream = config.apply(supp.get());
assertEquals(0, counter.get());
Iterator<Integer> iterator = stream.iterator();
assertEquals(0, counter.get());
if (iterator.hasNext())
iterator.next();
assertTrue(data.size() == 0 || counter.get() > 0);
counter.set(0);
stream = config.apply(supp.get());
Spliterator<Integer> spliterator = stream.spliterator();
assertEquals(0, counter.get());
spliterator.forEachRemaining(e -> {
});
assertTrue(data.size() == 0 || counter.get() > 0);
}
}
}
use of java8.util.Spliterator in project streamsupport by stefan-zobel.
the class DoublePipeline method forEachWithCancel.
@Override
final boolean forEachWithCancel(Spliterator<Double> spliterator, Sink<Double> sink) {
Spliterator.OfDouble spl = adapt(spliterator);
DoubleConsumer adaptedSink = adapt(sink);
boolean cancelled;
do {
} while (!(cancelled = sink.cancellationRequested()) && spl.tryAdvance(adaptedSink));
return cancelled;
}
use of java8.util.Spliterator in project streamsupport by stefan-zobel.
the class Spliterators method iterator.
// Iterators from Spliterators
/**
* Creates an {@code Iterator} from a {@code Spliterator}.
*
* <p>Traversal of elements should be accomplished through the iterator.
* The behaviour of traversal is undefined if the spliterator is operated
* after the iterator is returned.
*
* @param <T> Type of elements
* @param spliterator The spliterator
* @return An iterator
* @throws NullPointerException if the given spliterator is {@code null}
*/
public static <T> Iterator<T> iterator(Spliterator<? extends T> spliterator) {
Objects.requireNonNull(spliterator);
class Adapter implements Iterator<T>, Consumer<T> {
boolean valueReady = false;
T nextElement;
@Override
public void accept(T t) {
valueReady = true;
nextElement = t;
}
@Override
public boolean hasNext() {
if (!valueReady)
spliterator.tryAdvance(this);
return valueReady;
}
@Override
public T next() {
if (!valueReady && !hasNext())
throw new NoSuchElementException();
else {
valueReady = false;
return nextElement;
}
}
@Override
public void remove() {
throw new UnsupportedOperationException("remove");
}
}
return new Adapter();
}
Aggregations