Search in sources :

Example 31 with Spliterator

use of java.util.Spliterator in project nexus-public by sonatype.

the class DatastoreMetadataRebuilderTest method infiniteContinuation.

private Continuation infiniteContinuation(Object returnItem) {
    Continuation continuation = mock(Continuation.class);
    Iterator iterator = mock(Iterator.class);
    Spliterator spliterator = mock(Spliterator.class);
    when(continuation.spliterator()).thenReturn(spliterator);
    when(continuation.iterator()).thenReturn(iterator);
    when(iterator.hasNext()).thenReturn(true);
    when(iterator.next()).thenReturn(returnItem);
    return continuation;
}
Also used : Continuation(org.sonatype.nexus.common.entity.Continuation) Iterator(java.util.Iterator) Spliterator(java.util.Spliterator)

Example 32 with Spliterator

use of java.util.Spliterator in project jnosql-diana by eclipse.

the class SettingsConverter method success.

@Override
public Settings success(String value) {
    Config config = BeanManagers.getInstance(Config.class);
    final Spliterator<String> spliterator = config.getPropertyNames().spliterator();
    final String settingsPrefix = getSettingsPrefix(value);
    final Map<String, Object> settings = stream(spliterator, false).filter(isSettings(settingsPrefix)).distinct().collect(toMap(s -> s.replace(value + ".settings.", ""), s -> config.getValue(s, String.class)));
    return Settings.of(settings);
}
Also used : Converter(org.eclipse.microprofile.config.spi.Converter) Collectors.toMap(java.util.stream.Collectors.toMap) StreamSupport.stream(java.util.stream.StreamSupport.stream) Predicate(java.util.function.Predicate) Map(java.util.Map) BeanManagers(org.eclipse.jnosql.mapping.util.BeanManagers) Settings(jakarta.nosql.Settings) Config(org.eclipse.microprofile.config.Config) Spliterator(java.util.Spliterator) StringUtils(org.eclipse.jnosql.mapping.util.StringUtils) Config(org.eclipse.microprofile.config.Config)

Example 33 with Spliterator

use of java.util.Spliterator in project streamex by amaembo.

the class TestHelpers method checkSpliterator.

/*
     * Tests whether spliterators produced by given supplier produce the
     * expected result under various splittings
     * 
     * This test is single-threaded. Its behavior is randomized, but random seed
     * will be printed in case of failure, so the results could be reproduced
     */
public static <T> void checkSpliterator(String msg, List<T> expected, Supplier<Spliterator<T>> supplier) {
    List<T> seq = new ArrayList<>();
    // Test characteristics
    Spliterator<T> forCharacteristics = supplier.get();
    if (forCharacteristics.hasCharacteristics(Spliterator.SORTED)) {
        // must not fail
        forCharacteristics.getComparator();
    }
    assertTrue(forCharacteristics.estimateSize() >= 0);
    // Test forEachRemaining
    Spliterator<T> sequential = supplier.get();
    sequential.forEachRemaining(seq::add);
    assertFalse(msg, sequential.tryAdvance(t -> fail(msg + ": Advance called with " + t)));
    sequential.forEachRemaining(t -> fail(msg + ": Advance called with " + t));
    assertEquals(msg, expected, seq);
    // Test tryAdvance
    seq.clear();
    sequential = supplier.get();
    while (true) {
        AtomicBoolean called = new AtomicBoolean();
        boolean res = sequential.tryAdvance(t -> {
            seq.add(t);
            called.set(true);
        });
        if (res != called.get()) {
            fail(msg + (res ? ": Consumer not called, but spliterator returned true" : ": Consumer called, but spliterator returned false"));
        }
        if (!res)
            break;
    }
    assertFalse(msg, sequential.tryAdvance(t -> fail(msg + ": Advance called with " + t)));
    assertEquals(msg, expected, seq);
    // Test TailSpliterator
    if (sequential instanceof TailSpliterator) {
        seq.clear();
        TailSpliterator.forEachWithTail(supplier.get(), seq::add);
        assertEquals(msg, expected, seq);
        seq.clear();
        sequential = supplier.get();
        while (sequential != null) {
            sequential = TailSpliterator.tryAdvanceWithTail(sequential, seq::add);
        }
    }
    assertEquals(msg, expected, seq);
    // Test advance+remaining
    for (int i = 1; i < Math.min(4, expected.size() - 1); i++) {
        seq.clear();
        sequential = supplier.get();
        for (int j = 0; j < i; j++) assertTrue(msg, sequential.tryAdvance(seq::add));
        sequential.forEachRemaining(seq::add);
        assertEquals(msg, expected, seq);
    }
    // Test trySplit
    withRandom(r -> {
        repeat(500, n -> {
            Spliterator<T> spliterator = supplier.get();
            List<Spliterator<T>> spliterators = new ArrayList<>();
            spliterators.add(spliterator);
            int p = r.nextInt(10) + 2;
            for (int i = 0; i < p; i++) {
                int idx = r.nextInt(spliterators.size());
                Spliterator<T> split = spliterators.get(idx).trySplit();
                if (split != null)
                    spliterators.add(idx, split);
            }
            List<Integer> order = IntStreamEx.ofIndices(spliterators).boxed().toMutableList();
            Collections.shuffle(order, r);
            List<T> list = StreamEx.of(order).mapToEntry(idx -> {
                Spliterator<T> s = spliterators.get(idx);
                Stream.Builder<T> builder = Stream.builder();
                s.forEachRemaining(builder);
                assertFalse(msg, s.tryAdvance(t -> fail(msg + ": Advance called with " + t)));
                s.forEachRemaining(t -> fail(msg + ": Advance called with " + t));
                return builder.build();
            }).sortedBy(Entry::getKey).values().flatMap(Function.identity()).toList();
            assertEquals(msg, expected, list);
        });
        repeat(500, n -> {
            Spliterator<T> spliterator = supplier.get();
            List<Spliterator<T>> spliterators = new ArrayList<>();
            spliterators.add(spliterator);
            int p = r.nextInt(30) + 2;
            for (int i = 0; i < p; i++) {
                int idx = r.nextInt(spliterators.size());
                Spliterator<T> split = spliterators.get(idx).trySplit();
                if (split != null)
                    spliterators.add(idx, split);
            }
            List<List<T>> results = StreamEx.<List<T>>generate(ArrayList::new).limit(spliterators.size()).toMutableList();
            int count = spliterators.size();
            while (count > 0) {
                int i;
                do {
                    i = r.nextInt(spliterators.size());
                    spliterator = spliterators.get(i);
                } while (spliterator == null);
                if (!spliterator.tryAdvance(results.get(i)::add)) {
                    spliterators.set(i, null);
                    count--;
                }
            }
            List<T> list = StreamEx.of(results).flatMap(List::stream).toList();
            assertEquals(msg, expected, list);
        });
    });
}
Also used : IntStream(java.util.stream.IntStream) Spliterators(java.util.Spliterators) IntConsumer(java.util.function.IntConsumer) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Random(java.util.Random) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) ThreadLocalRandom(java.util.concurrent.ThreadLocalRandom) Assert.fail(org.junit.Assert.fail) Collector(java.util.stream.Collector) TailSpliterator(one.util.streamex.Internals.TailSpliterator) LongStream(java.util.stream.LongStream) Predicate(java.util.function.Predicate) Assert.assertNotNull(org.junit.Assert.assertNotNull) Internals.finished(one.util.streamex.Internals.finished) Set(java.util.Set) Assert.assertTrue(org.junit.Assert.assertTrue) Collectors(java.util.stream.Collectors) Objects(java.util.Objects) Consumer(java.util.function.Consumer) List(java.util.List) Stream(java.util.stream.Stream) Assert.assertNull(org.junit.Assert.assertNull) Assert.assertFalse(org.junit.Assert.assertFalse) Entry(java.util.Map.Entry) Comparator(java.util.Comparator) Collections(java.util.Collections) Spliterator(java.util.Spliterator) Assert.assertEquals(org.junit.Assert.assertEquals) ConcurrentLinkedQueue(java.util.concurrent.ConcurrentLinkedQueue) ComparisonFailure(org.junit.ComparisonFailure) ArrayList(java.util.ArrayList) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) TailSpliterator(one.util.streamex.Internals.TailSpliterator) IntStream(java.util.stream.IntStream) LongStream(java.util.stream.LongStream) Stream(java.util.stream.Stream) ArrayList(java.util.ArrayList) List(java.util.List) TailSpliterator(one.util.streamex.Internals.TailSpliterator) Spliterator(java.util.Spliterator)

Example 34 with Spliterator

use of java.util.Spliterator in project streamex by amaembo.

the class LongStreamExTest method testBasics.

@Test
public void testBasics() {
    assertFalse(LongStreamEx.of(1).isParallel());
    assertTrue(LongStreamEx.of(1).parallel().isParallel());
    assertFalse(LongStreamEx.of(1).parallel().sequential().isParallel());
    AtomicInteger i = new AtomicInteger();
    try (LongStreamEx s = LongStreamEx.of(1).onClose(i::incrementAndGet)) {
        assertEquals(1, s.count());
    }
    assertEquals(1, i.get());
    assertEquals(6, LongStreamEx.range(0, 4).sum());
    assertEquals(3, LongStreamEx.range(0, 4).max().getAsLong());
    assertEquals(0, LongStreamEx.range(0, 4).min().getAsLong());
    assertEquals(1.5, LongStreamEx.range(0, 4).average().getAsDouble(), 0.000001);
    assertEquals(4, LongStreamEx.range(0, 4).summaryStatistics().getCount());
    assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.range(0, 5).skip(1).limit(3).toArray());
    assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.of(3, 1, 2).sorted().toArray());
    assertArrayEquals(new long[] { 1, 2, 3 }, LongStreamEx.of(1, 2, 1, 3, 2).distinct().toArray());
    assertArrayEquals(new int[] { 2, 4, 6 }, LongStreamEx.range(1, 4).mapToInt(x -> (int) x * 2).toArray());
    assertArrayEquals(new long[] { 2, 4, 6 }, LongStreamEx.range(1, 4).map(x -> x * 2).toArray());
    assertArrayEquals(new double[] { 2, 4, 6 }, LongStreamEx.range(1, 4).mapToDouble(x -> x * 2).toArray(), 0.0);
    assertArrayEquals(new long[] { 1, 3 }, LongStreamEx.range(0, 5).filter(x -> x % 2 == 1).toArray());
    assertEquals(6, LongStreamEx.of(1, 2, 3).reduce(Long::sum).getAsLong());
    assertEquals(Long.MAX_VALUE, LongStreamEx.rangeClosed(1, Long.MAX_VALUE).spliterator().getExactSizeIfKnown());
    assertTrue(LongStreamEx.of(1, 2, 3).spliterator().hasCharacteristics(Spliterator.ORDERED));
    assertFalse(LongStreamEx.of(1, 2, 3).unordered().spliterator().hasCharacteristics(Spliterator.ORDERED));
    OfLong iterator = LongStreamEx.of(1, 2, 3).iterator();
    assertEquals(1L, iterator.nextLong());
    assertEquals(2L, iterator.nextLong());
    assertEquals(3L, iterator.nextLong());
    assertFalse(iterator.hasNext());
    AtomicInteger idx = new AtomicInteger();
    long[] result = new long[500];
    LongStreamEx.range(1000).atLeast(500).parallel().forEachOrdered(val -> result[idx.getAndIncrement()] = val);
    assertArrayEquals(LongStreamEx.range(500, 1000).toArray(), result);
    assertTrue(LongStreamEx.empty().noneMatch(x -> true));
    assertFalse(LongStreamEx.of(1).noneMatch(x -> true));
    assertTrue(LongStreamEx.of(1).noneMatch(x -> false));
}
Also used : MethodSorters(org.junit.runners.MethodSorters) Arrays(java.util.Arrays) LongBinaryOperator(java.util.function.LongBinaryOperator) Spliterators(java.util.Spliterators) Assert.assertThrows(org.junit.Assert.assertThrows) Scanner(java.util.Scanner) Random(java.util.Random) Builder(java.util.stream.LongStream.Builder) Function(java.util.function.Function) Supplier(java.util.function.Supplier) ArrayList(java.util.ArrayList) HashSet(java.util.HashSet) Assert.assertSame(org.junit.Assert.assertSame) OptionalLong(java.util.OptionalLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) Map(java.util.Map) Assert.assertArrayEquals(org.junit.Assert.assertArrayEquals) OfLong(java.util.PrimitiveIterator.OfLong) LongToDoubleFunction(java.util.function.LongToDoubleFunction) LongToIntFunction(java.util.function.LongToIntFunction) LongStream(java.util.stream.LongStream) LongStreamEx(one.util.streamex.LongStreamEx) LongFunction(java.util.function.LongFunction) TestHelpers.checkSpliterator(one.util.streamex.TestHelpers.checkSpliterator) Assert.assertTrue(org.junit.Assert.assertTrue) Test(org.junit.Test) Collectors(java.util.stream.Collectors) LongConsumer(java.util.function.LongConsumer) TestHelpers.streamEx(one.util.streamex.TestHelpers.streamEx) AtomicLong(java.util.concurrent.atomic.AtomicLong) List(java.util.List) LongUnaryOperator(java.util.function.LongUnaryOperator) StreamEx(one.util.streamex.StreamEx) Assert.assertFalse(org.junit.Assert.assertFalse) LongBuffer(java.nio.LongBuffer) IntStreamEx(one.util.streamex.IntStreamEx) TestHelpers.longStreamEx(one.util.streamex.TestHelpers.longStreamEx) Comparator(java.util.Comparator) FixMethodOrder(org.junit.FixMethodOrder) Spliterator(java.util.Spliterator) Assert.assertEquals(org.junit.Assert.assertEquals) OfLong(java.util.PrimitiveIterator.OfLong) AtomicInteger(java.util.concurrent.atomic.AtomicInteger) LongStreamEx(one.util.streamex.LongStreamEx) OptionalLong(java.util.OptionalLong) OfLong(java.util.PrimitiveIterator.OfLong) AtomicLong(java.util.concurrent.atomic.AtomicLong) Test(org.junit.Test)

Example 35 with Spliterator

use of java.util.Spliterator in project streamex by amaembo.

the class IntStreamEx method of.

/**
 * Returns a sequential ordered {@code IntStreamEx} backed by the content of
 * given {@link InputStream}.
 *
 * <p>
 * The resulting stream contains int values between 0 and 255 (0xFF)
 * inclusive, as they are returned by the {@link InputStream#read()} method.
 * If you want to get <code>byte</code> values (e.g. -1 instead of 255),
 * simply cast the stream elements like <code>.map(b -&gt; (byte)b)</code>.
 * The terminal -1 value is excluded from the resulting stream.
 *
 * <p>
 * If the underlying {@code InputStream} throws an {@link IOException}
 * during the stream traversal, it will be rethrown as
 * {@link UncheckedIOException}.
 *
 * <p>
 * When the returned {@code IntStreamEx} is closed the original
 * {@code InputStream} is closed as well. If {@link InputStream#close()}
 * method throws an {@code IOException}, it will be rethrown as
 * {@link UncheckedIOException}.
 *
 * @param is an {@code InputStream} to create an {@code IntStreamEx} on.
 * @return the new stream
 * @see #asByteInputStream()
 * @since 0.6.1
 */
public static IntStreamEx of(InputStream is) {
    Spliterator.OfInt spliterator = new AbstractIntSpliterator(Long.MAX_VALUE, Spliterator.ORDERED | Spliterator.NONNULL) {

        @Override
        public boolean tryAdvance(IntConsumer action) {
            try {
                int next = is.read();
                if (next == -1)
                    return false;
                action.accept(next);
                return true;
            } catch (IOException e) {
                throw new UncheckedIOException(e);
            }
        }
    };
    return of(spliterator).onClose(() -> {
        try {
            is.close();
        } catch (IOException e) {
            throw new UncheckedIOException(e);
        }
    });
}
Also used : UncheckedIOException(java.io.UncheckedIOException) UncheckedIOException(java.io.UncheckedIOException) IOException(java.io.IOException) AbstractIntSpliterator(java.util.Spliterators.AbstractIntSpliterator) Spliterator(java.util.Spliterator) AbstractIntSpliterator(java.util.Spliterators.AbstractIntSpliterator) IntConsumer(java.util.function.IntConsumer) ObjIntConsumer(java.util.function.ObjIntConsumer)

Aggregations

Spliterator (java.util.Spliterator)109 List (java.util.List)43 ArrayList (java.util.ArrayList)35 HashSet (java.util.HashSet)31 IntConsumer (java.util.function.IntConsumer)31 Set (java.util.Set)26 Function (java.util.function.Function)24 Objects (java.util.Objects)23 Spliterators (java.util.Spliterators)23 Stream (java.util.stream.Stream)22 Collectors (java.util.stream.Collectors)21 Iterator (java.util.Iterator)20 Map (java.util.Map)20 Consumer (java.util.function.Consumer)20 Comparator (java.util.Comparator)18 LongConsumer (java.util.function.LongConsumer)18 StreamSupport (java.util.stream.StreamSupport)18 Arrays (java.util.Arrays)17 Supplier (java.util.function.Supplier)17 Collections (java.util.Collections)16