Search in sources :

Example 46 with Spliterator

use of java.util.Spliterator in project jdk8u_jdk by JetBrains.

the class StreamSpliteratorTest method testLongSplitting.

//
public void testLongSplitting() {
    List<Consumer<LongStream>> terminalOps = Arrays.asList(s -> s.toArray(), s -> s.forEach(e -> {
    }), s -> s.reduce(Long::sum));
    List<UnaryOperator<LongStream>> intermediateOps = Arrays.asList(s -> s.parallel(), // The following ensures the wrapping spliterator is tested
    s -> s.map(i -> i).parallel());
    for (int i = 0; i < terminalOps.size(); i++) {
        Consumer<LongStream> terminalOp = terminalOps.get(i);
        setContext("termOpIndex", i);
        for (int j = 0; j < intermediateOps.size(); j++) {
            setContext("intOpIndex", j);
            UnaryOperator<LongStream> intermediateOp = intermediateOps.get(j);
            for (boolean proxyEstimateSize : new boolean[] { false, true }) {
                setContext("proxyEstimateSize", proxyEstimateSize);
                // Size is assumed to be larger than the target size for no splitting
                // @@@ Need way to obtain the target size
                Spliterator.OfLong sp = intermediateOp.apply(LongStream.range(0, 1000)).spliterator();
                ProxyNoExactSizeSpliterator.OfLong psp = new ProxyNoExactSizeSpliterator.OfLong(sp, proxyEstimateSize);
                LongStream s = StreamSupport.longStream(psp, true);
                terminalOp.accept(s);
                Assert.assertTrue(psp.splits > 0, String.format("Number of splits should be greater that zero when proxyEstimateSize is %s", proxyEstimateSize));
                Assert.assertTrue(psp.prefixSplits > 0, String.format("Number of non-null prefix splits should be greater that zero when proxyEstimateSize is %s", proxyEstimateSize));
                Assert.assertTrue(psp.sizeOnTraversal < 1000, String.format("Size on traversal of last split should be less than the size of the list, %d, when proxyEstimateSize is %s", 1000, proxyEstimateSize));
            }
        }
    }
}
Also used : IntStream(java.util.stream.IntStream) Arrays(java.util.Arrays) SpliteratorTestHelper(java.util.stream.SpliteratorTestHelper) IntConsumer(java.util.function.IntConsumer) UnaryOperator(java.util.function.UnaryOperator) Test(org.testng.annotations.Test) DoubleConsumer(java.util.function.DoubleConsumer) Function(java.util.function.Function) Assert(org.testng.Assert) LambdaTestHelpers.dpEven(java.util.stream.LambdaTestHelpers.dpEven) LambdaTestHelpers.irDoubler(java.util.stream.LambdaTestHelpers.irDoubler) StreamSupport(java.util.stream.StreamSupport) IntStreamTestDataProvider(java.util.stream.IntStreamTestDataProvider) LambdaTestHelpers.countTo(java.util.stream.LambdaTestHelpers.countTo) LongStream(java.util.stream.LongStream) LambdaTestHelpers.lpEven(java.util.stream.LambdaTestHelpers.lpEven) DoubleStreamTestDataProvider(java.util.stream.DoubleStreamTestDataProvider) TestData(java.util.stream.TestData) StreamTestDataProvider(java.util.stream.StreamTestDataProvider) LambdaTestHelpers.permuteStreamFunctions(java.util.stream.LambdaTestHelpers.permuteStreamFunctions) LongConsumer(java.util.function.LongConsumer) DoubleStream(java.util.stream.DoubleStream) Consumer(java.util.function.Consumer) List(java.util.List) Stream(java.util.stream.Stream) LambdaTestHelpers(java.util.stream.LambdaTestHelpers) OpTestCase(java.util.stream.OpTestCase) LambdaTestHelpers.mDoubler(java.util.stream.LambdaTestHelpers.mDoubler) LongStreamTestDataProvider(java.util.stream.LongStreamTestDataProvider) LambdaTestHelpers.pEven(java.util.stream.LambdaTestHelpers.pEven) LambdaTestHelpers.ipEven(java.util.stream.LambdaTestHelpers.ipEven) Comparator(java.util.Comparator) Spliterator(java.util.Spliterator) LongStream(java.util.stream.LongStream) IntConsumer(java.util.function.IntConsumer) DoubleConsumer(java.util.function.DoubleConsumer) LongConsumer(java.util.function.LongConsumer) Consumer(java.util.function.Consumer) UnaryOperator(java.util.function.UnaryOperator) Spliterator(java.util.Spliterator)

Example 47 with Spliterator

use of java.util.Spliterator in project judge by zjnu-acm.

the class MockGenerator method takeWhile.

private static <T> Stream<T> takeWhile(Stream<T> stream, Predicate<? super T> p) {
    class UnorderedWhileSpliterator extends Spliterators.AbstractSpliterator<T> implements Consumer<T> {

        private static final int CANCEL_CHECK_COUNT = 63;

        private final Spliterator<T> s;

        private int count;

        private T t;

        private final AtomicBoolean cancel = new AtomicBoolean();

        private boolean takeOrDrop = true;

        UnorderedWhileSpliterator(Spliterator<T> s) {
            super(s.estimateSize(), s.characteristics() & ~(Spliterator.SIZED | Spliterator.SUBSIZED));
            this.s = s;
        }

        @Override
        @SuppressWarnings("NestedAssignment")
        public boolean tryAdvance(Consumer<? super T> action) {
            boolean test = true;
            if (// If can take
            takeOrDrop && // and if not cancelled
            (count != 0 || !cancel.get()) && // and if advanced one element
            s.tryAdvance(this) && (test = p.test(t))) {
                // and test on element passes
                // then accept element
                action.accept(t);
                return true;
            } else {
                // Taking is finished
                takeOrDrop = false;
                // only if test of element failed (short-circuited)
                if (!test) {
                    cancel.set(true);
                }
                return false;
            }
        }

        @Override
        public Comparator<? super T> getComparator() {
            return s.getComparator();
        }

        @Override
        public void accept(T t) {
            count = (count + 1) & CANCEL_CHECK_COUNT;
            this.t = t;
        }

        @Override
        public Spliterator<T> trySplit() {
            return null;
        }
    }
    return StreamSupport.stream(new UnorderedWhileSpliterator(stream.spliterator()), stream.isParallel()).onClose(stream::close);
}
Also used : AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Consumer(java.util.function.Consumer) Spliterator(java.util.Spliterator)

Example 48 with Spliterator

use of java.util.Spliterator in project janusgraph by JanusGraph.

the class ElasticSearchIndex method getFilter.

public Map<String, Object> getFilter(Condition<?> condition, KeyInformation.StoreRetriever information) {
    if (condition instanceof PredicateCondition) {
        final PredicateCondition<String, ?> atom = (PredicateCondition) condition;
        Object value = atom.getValue();
        final String key = atom.getKey();
        final JanusGraphPredicate predicate = atom.getPredicate();
        if (value == null && predicate == Cmp.NOT_EQUAL) {
            return compat.exists(key);
        } else if (value instanceof Number) {
            Preconditions.checkArgument(predicate instanceof Cmp, "Relation not supported on numeric types: %s", predicate);
            return getRelationFromCmp((Cmp) predicate, key, value);
        } else if (value instanceof String) {
            final Mapping mapping = getStringMapping(information.get(key));
            final String fieldName;
            if (mapping == Mapping.TEXT && !(Text.HAS_CONTAINS.contains(predicate) || predicate instanceof Cmp))
                throw new IllegalArgumentException("Text mapped string values only support CONTAINS and Compare queries and not: " + predicate);
            if (mapping == Mapping.STRING && Text.HAS_CONTAINS.contains(predicate))
                throw new IllegalArgumentException("String mapped string values do not support CONTAINS queries: " + predicate);
            if (mapping == Mapping.TEXTSTRING && !(Text.HAS_CONTAINS.contains(predicate) || (predicate instanceof Cmp && predicate != Cmp.EQUAL))) {
                fieldName = getDualMappingName(key);
            } else {
                fieldName = key;
            }
            if (predicate == Text.CONTAINS || predicate == Cmp.EQUAL) {
                return compat.match(fieldName, value);
            } else if (predicate == Text.NOT_CONTAINS) {
                return compat.boolMust(ImmutableList.of(compat.exists(fieldName), compat.boolMustNot(compat.match(fieldName, value))));
            } else if (predicate == Text.CONTAINS_PHRASE) {
                return compat.matchPhrase(fieldName, value);
            } else if (predicate == Text.NOT_CONTAINS_PHRASE) {
                return compat.boolMust(ImmutableList.of(compat.exists(fieldName), compat.boolMustNot(compat.matchPhrase(fieldName, value))));
            } else if (predicate == Text.CONTAINS_PREFIX) {
                if (!ParameterType.TEXT_ANALYZER.hasParameter(information.get(key).getParameters()))
                    value = ((String) value).toLowerCase();
                return compat.prefix(fieldName, value);
            } else if (predicate == Text.NOT_CONTAINS_PREFIX) {
                if (!ParameterType.TEXT_ANALYZER.hasParameter(information.get(key).getParameters()))
                    value = ((String) value).toLowerCase();
                return compat.boolMust(ImmutableList.of(compat.exists(fieldName), compat.boolMustNot(compat.prefix(fieldName, value))));
            } else if (predicate == Text.CONTAINS_REGEX) {
                if (!ParameterType.TEXT_ANALYZER.hasParameter(information.get(key).getParameters()))
                    value = ((String) value).toLowerCase();
                return compat.regexp(fieldName, value);
            } else if (predicate == Text.NOT_CONTAINS_REGEX) {
                if (!ParameterType.TEXT_ANALYZER.hasParameter(information.get(key).getParameters()))
                    value = ((String) value).toLowerCase();
                return compat.boolMust(ImmutableList.of(compat.exists(fieldName), compat.boolMustNot(compat.regexp(fieldName, value))));
            } else if (predicate == Text.PREFIX) {
                return compat.prefix(fieldName, value);
            } else if (predicate == Text.NOT_PREFIX) {
                return compat.boolMust(ImmutableList.of(compat.exists(fieldName), compat.boolMustNot(compat.prefix(fieldName, value))));
            } else if (predicate == Text.REGEX) {
                return compat.regexp(fieldName, value);
            } else if (predicate == Text.NOT_REGEX) {
                return compat.boolMust(ImmutableList.of(compat.exists(fieldName), compat.boolMustNot(compat.regexp(fieldName, value))));
            } else if (predicate == Cmp.NOT_EQUAL) {
                return compat.boolMustNot(compat.match(fieldName, value));
            } else if (predicate == Text.FUZZY || predicate == Text.CONTAINS_FUZZY) {
                return compat.fuzzyMatch(fieldName, value);
            } else if (predicate == Text.NOT_FUZZY || predicate == Text.NOT_CONTAINS_FUZZY) {
                return compat.boolMust(ImmutableList.of(compat.exists(fieldName), compat.boolMustNot(compat.fuzzyMatch(fieldName, value))));
            } else if (predicate == Cmp.LESS_THAN) {
                return compat.lt(fieldName, value);
            } else if (predicate == Cmp.LESS_THAN_EQUAL) {
                return compat.lte(fieldName, value);
            } else if (predicate == Cmp.GREATER_THAN) {
                return compat.gt(fieldName, value);
            } else if (predicate == Cmp.GREATER_THAN_EQUAL) {
                return compat.gte(fieldName, value);
            } else
                throw new IllegalArgumentException("Predicate is not supported for string value: " + predicate);
        } else if (value instanceof Geoshape && Mapping.getMapping(information.get(key)) == Mapping.DEFAULT) {
            // geopoint
            final Geoshape shape = (Geoshape) value;
            Preconditions.checkArgument(predicate instanceof Geo && predicate != Geo.CONTAINS, "Relation not supported on geopoint types: %s", predicate);
            final Map<String, Object> query;
            switch(shape.getType()) {
                case CIRCLE:
                    final Geoshape.Point center = shape.getPoint();
                    query = compat.geoDistance(key, center.getLatitude(), center.getLongitude(), shape.getRadius());
                    break;
                case BOX:
                    final Geoshape.Point southwest = shape.getPoint(0);
                    final Geoshape.Point northeast = shape.getPoint(1);
                    query = compat.geoBoundingBox(key, southwest.getLatitude(), southwest.getLongitude(), northeast.getLatitude(), northeast.getLongitude());
                    break;
                case POLYGON:
                    final List<List<Double>> points = IntStream.range(0, shape.size()).mapToObj(i -> ImmutableList.of(shape.getPoint(i).getLongitude(), shape.getPoint(i).getLatitude())).collect(Collectors.toList());
                    query = compat.geoPolygon(key, points);
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported or invalid search shape type for geopoint: " + shape.getType());
            }
            return predicate == Geo.DISJOINT ? compat.boolMustNot(query) : query;
        } else if (value instanceof Geoshape) {
            Preconditions.checkArgument(predicate instanceof Geo, "Relation not supported on geoshape types: %s", predicate);
            final Geoshape shape = (Geoshape) value;
            final Map<String, Object> geo;
            switch(shape.getType()) {
                case CIRCLE:
                    final Geoshape.Point center = shape.getPoint();
                    geo = ImmutableMap.of(ES_TYPE_KEY, "circle", ES_GEO_COORDS_KEY, ImmutableList.of(center.getLongitude(), center.getLatitude()), "radius", shape.getRadius() + "km");
                    break;
                case BOX:
                    final Geoshape.Point southwest = shape.getPoint(0);
                    final Geoshape.Point northeast = shape.getPoint(1);
                    geo = ImmutableMap.of(ES_TYPE_KEY, "envelope", ES_GEO_COORDS_KEY, ImmutableList.of(ImmutableList.of(southwest.getLongitude(), northeast.getLatitude()), ImmutableList.of(northeast.getLongitude(), southwest.getLatitude())));
                    break;
                case LINE:
                    final List lineCoords = IntStream.range(0, shape.size()).mapToObj(i -> ImmutableList.of(shape.getPoint(i).getLongitude(), shape.getPoint(i).getLatitude())).collect(Collectors.toList());
                    geo = ImmutableMap.of(ES_TYPE_KEY, "linestring", ES_GEO_COORDS_KEY, lineCoords);
                    break;
                case POLYGON:
                    final List polyCoords = IntStream.range(0, shape.size()).mapToObj(i -> ImmutableList.of(shape.getPoint(i).getLongitude(), shape.getPoint(i).getLatitude())).collect(Collectors.toList());
                    geo = ImmutableMap.of(ES_TYPE_KEY, "polygon", ES_GEO_COORDS_KEY, ImmutableList.of(polyCoords));
                    break;
                case POINT:
                    geo = ImmutableMap.of(ES_TYPE_KEY, "point", ES_GEO_COORDS_KEY, ImmutableList.of(shape.getPoint().getLongitude(), shape.getPoint().getLatitude()));
                    break;
                default:
                    throw new IllegalArgumentException("Unsupported or invalid search shape type: " + shape.getType());
            }
            return compat.geoShape(key, geo, (Geo) predicate);
        } else if (value instanceof Date || value instanceof Instant) {
            Preconditions.checkArgument(predicate instanceof Cmp, "Relation not supported on date types: %s", predicate);
            if (value instanceof Instant) {
                value = Date.from((Instant) value);
            }
            return getRelationFromCmp((Cmp) predicate, key, value);
        } else if (value instanceof Boolean) {
            final Cmp numRel = (Cmp) predicate;
            switch(numRel) {
                case EQUAL:
                    return compat.term(key, value);
                case NOT_EQUAL:
                    return compat.boolMustNot(compat.term(key, value));
                default:
                    throw new IllegalArgumentException("Boolean types only support EQUAL or NOT_EQUAL");
            }
        } else if (value instanceof UUID) {
            if (predicate == Cmp.EQUAL) {
                return compat.term(key, value);
            } else if (predicate == Cmp.NOT_EQUAL) {
                return compat.boolMustNot(compat.term(key, value));
            } else {
                throw new IllegalArgumentException("Only equal or not equal is supported for UUIDs: " + predicate);
            }
        } else
            throw new IllegalArgumentException("Unsupported type: " + value);
    } else if (condition instanceof Not) {
        return compat.boolMustNot(getFilter(((Not) condition).getChild(), information));
    } else if (condition instanceof And) {
        final List queries = StreamSupport.stream(condition.getChildren().spliterator(), false).map(c -> getFilter(c, information)).collect(Collectors.toList());
        return compat.boolMust(queries);
    } else if (condition instanceof Or) {
        final List queries = StreamSupport.stream(condition.getChildren().spliterator(), false).map(c -> getFilter(c, information)).collect(Collectors.toList());
        return compat.boolShould(queries);
    } else
        throw new IllegalArgumentException("Invalid condition: " + condition);
}
Also used : PredicateCondition(org.janusgraph.graphdb.query.condition.PredicateCondition) INDEX_MAX_RESULT_SET_SIZE(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.INDEX_MAX_RESULT_SET_SIZE) Arrays(java.util.Arrays) RestClientBuilder(org.elasticsearch.client.RestClientBuilder) Date(java.util.Date) Spliterators(java.util.Spliterators) ES_LANG_KEY(org.janusgraph.diskstorage.es.ElasticSearchConstants.ES_LANG_KEY) LoggerFactory(org.slf4j.LoggerFactory) ConfigOption(org.janusgraph.diskstorage.configuration.ConfigOption) Geoshape(org.janusgraph.core.attribute.Geoshape) AbstractESCompat(org.janusgraph.diskstorage.es.compat.AbstractESCompat) ESCompatUtils(org.janusgraph.diskstorage.es.compat.ESCompatUtils) BaseTransaction(org.janusgraph.diskstorage.BaseTransaction) IndexProvider(org.janusgraph.diskstorage.indexing.IndexProvider) Cardinality(org.janusgraph.core.Cardinality) IndexEntry(org.janusgraph.diskstorage.indexing.IndexEntry) KeyInformation(org.janusgraph.diskstorage.indexing.KeyInformation) Map(java.util.Map) IndexQuery(org.janusgraph.diskstorage.indexing.IndexQuery) LinkedListMultimap(com.google.common.collect.LinkedListMultimap) And(org.janusgraph.graphdb.query.condition.And) Mapping(org.janusgraph.core.schema.Mapping) ImmutableMap(com.google.common.collect.ImmutableMap) Collection(java.util.Collection) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) ES_GEO_COORDS_KEY(org.janusgraph.diskstorage.es.ElasticSearchConstants.ES_GEO_COORDS_KEY) UUID(java.util.UUID) Instant(java.time.Instant) Collectors(java.util.stream.Collectors) Sets(com.google.common.collect.Sets) UncheckedIOException(java.io.UncheckedIOException) Objects(java.util.Objects) List(java.util.List) ES_SCRIPT_KEY(org.janusgraph.diskstorage.es.ElasticSearchConstants.ES_SCRIPT_KEY) Parameter(org.janusgraph.core.schema.Parameter) Stream(java.util.stream.Stream) INDEX_NAME(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.INDEX_NAME) HttpAuthTypes(org.janusgraph.diskstorage.es.rest.util.HttpAuthTypes) Spliterator(java.util.Spliterator) PreInitializeConfigOptions(org.janusgraph.graphdb.configuration.PreInitializeConfigOptions) Not(org.janusgraph.graphdb.query.condition.Not) IntStream(java.util.stream.IntStream) ConfigNamespace(org.janusgraph.diskstorage.configuration.ConfigNamespace) Condition(org.janusgraph.graphdb.query.condition.Condition) AttributeUtils(org.janusgraph.graphdb.database.serialize.AttributeUtils) HashMap(java.util.HashMap) Multimap(com.google.common.collect.Multimap) Function(java.util.function.Function) Iterators(com.google.common.collect.Iterators) ArrayList(java.util.ArrayList) TemporaryBackendException(org.janusgraph.diskstorage.TemporaryBackendException) Rectangle(org.locationtech.spatial4j.shape.Rectangle) ImmutableList(com.google.common.collect.ImmutableList) Cmp(org.janusgraph.core.attribute.Cmp) IndexFeatures(org.janusgraph.diskstorage.indexing.IndexFeatures) Or(org.janusgraph.graphdb.query.condition.Or) JanusGraphException(org.janusgraph.core.JanusGraphException) StreamSupport(java.util.stream.StreamSupport) Geo(org.janusgraph.core.attribute.Geo) BackendException(org.janusgraph.diskstorage.BackendException) JanusGraphPredicate(org.janusgraph.graphdb.query.JanusGraphPredicate) Logger(org.slf4j.Logger) Iterator(java.util.Iterator) Configuration(org.janusgraph.diskstorage.configuration.Configuration) BaseTransactionConfigurable(org.janusgraph.diskstorage.BaseTransactionConfigurable) RawQuery(org.janusgraph.diskstorage.indexing.RawQuery) ES_TYPE_KEY(org.janusgraph.diskstorage.es.ElasticSearchConstants.ES_TYPE_KEY) IOException(java.io.IOException) DefaultTransaction(org.janusgraph.diskstorage.util.DefaultTransaction) ES_DOC_KEY(org.janusgraph.diskstorage.es.ElasticSearchConstants.ES_DOC_KEY) Text(org.janusgraph.core.attribute.Text) BaseTransactionConfig(org.janusgraph.diskstorage.BaseTransactionConfig) ESScriptResponse(org.janusgraph.diskstorage.es.script.ESScriptResponse) ConfigOption.disallowEmpty(org.janusgraph.diskstorage.configuration.ConfigOption.disallowEmpty) Preconditions(com.google.common.base.Preconditions) IndexMapping(org.janusgraph.diskstorage.es.mapping.IndexMapping) ParameterType(org.janusgraph.graphdb.types.ParameterType) PermanentBackendException(org.janusgraph.diskstorage.PermanentBackendException) INDEX_NS(org.janusgraph.graphdb.configuration.GraphDatabaseConfiguration.INDEX_NS) IndexMutation(org.janusgraph.diskstorage.indexing.IndexMutation) Or(org.janusgraph.graphdb.query.condition.Or) Mapping(org.janusgraph.core.schema.Mapping) IndexMapping(org.janusgraph.diskstorage.es.mapping.IndexMapping) JanusGraphPredicate(org.janusgraph.graphdb.query.JanusGraphPredicate) List(java.util.List) ArrayList(java.util.ArrayList) ImmutableList(com.google.common.collect.ImmutableList) UUID(java.util.UUID) PredicateCondition(org.janusgraph.graphdb.query.condition.PredicateCondition) Cmp(org.janusgraph.core.attribute.Cmp) Instant(java.time.Instant) Geoshape(org.janusgraph.core.attribute.Geoshape) Date(java.util.Date) Geo(org.janusgraph.core.attribute.Geo) Not(org.janusgraph.graphdb.query.condition.Not) And(org.janusgraph.graphdb.query.condition.And) Map(java.util.Map) ImmutableMap(com.google.common.collect.ImmutableMap) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) HashMap(java.util.HashMap)

Example 49 with Spliterator

use of java.util.Spliterator in project Bytecoder by mirkosertic.

the class DistinctOps method makeRef.

/**
 * Appends a "distinct" operation to the provided stream, and returns the
 * new stream.
 *
 * @param <T> the type of both input and output elements
 * @param upstream a reference stream with element type T
 * @return the new stream
 */
static <T> ReferencePipeline<T, T> makeRef(AbstractPipeline<?, T, ?> upstream) {
    return new ReferencePipeline.StatefulOp<T, T>(upstream, StreamShape.REFERENCE, StreamOpFlag.IS_DISTINCT | StreamOpFlag.NOT_SIZED) {

        <P_IN> Node<T> reduce(PipelineHelper<T> helper, Spliterator<P_IN> spliterator) {
            // If the stream is SORTED then it should also be ORDERED so the following will also
            // preserve the sort order
            TerminalOp<T, LinkedHashSet<T>> reduceOp = ReduceOps.<T, LinkedHashSet<T>>makeRef(LinkedHashSet::new, LinkedHashSet::add, LinkedHashSet::addAll);
            return Nodes.node(reduceOp.evaluateParallel(helper, spliterator));
        }

        @Override
        <P_IN> Node<T> opEvaluateParallel(PipelineHelper<T> helper, Spliterator<P_IN> spliterator, IntFunction<T[]> generator) {
            if (StreamOpFlag.DISTINCT.isKnown(helper.getStreamAndOpFlags())) {
                // No-op
                return helper.evaluate(spliterator, false, generator);
            } else if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
                return reduce(helper, spliterator);
            } else {
                // Holder of null state since ConcurrentHashMap does not support null values
                AtomicBoolean seenNull = new AtomicBoolean(false);
                ConcurrentHashMap<T, Boolean> map = new ConcurrentHashMap<>();
                TerminalOp<T, Void> forEachOp = ForEachOps.makeRef(t -> {
                    if (t == null)
                        seenNull.set(true);
                    else
                        map.putIfAbsent(t, Boolean.TRUE);
                }, false);
                forEachOp.evaluateParallel(helper, spliterator);
                // If null has been seen then copy the key set into a HashSet that supports null values
                // and add null
                Set<T> keys = map.keySet();
                if (seenNull.get()) {
                    // TODO Implement a more efficient set-union view, rather than copying
                    keys = new HashSet<>(keys);
                    keys.add(null);
                }
                return Nodes.node(keys);
            }
        }

        @Override
        <P_IN> Spliterator<T> opEvaluateParallelLazy(PipelineHelper<T> helper, Spliterator<P_IN> spliterator) {
            if (StreamOpFlag.DISTINCT.isKnown(helper.getStreamAndOpFlags())) {
                // No-op
                return helper.wrapSpliterator(spliterator);
            } else if (StreamOpFlag.ORDERED.isKnown(helper.getStreamAndOpFlags())) {
                // Not lazy, barrier required to preserve order
                return reduce(helper, spliterator).spliterator();
            } else {
                // Lazy
                return new StreamSpliterators.DistinctSpliterator<>(helper.wrapSpliterator(spliterator));
            }
        }

        @Override
        Sink<T> opWrapSink(int flags, Sink<T> sink) {
            Objects.requireNonNull(sink);
            if (StreamOpFlag.DISTINCT.isKnown(flags)) {
                return sink;
            } else if (StreamOpFlag.SORTED.isKnown(flags)) {
                return new Sink.ChainedReference<T, T>(sink) {

                    boolean seenNull;

                    T lastSeen;

                    @Override
                    public void begin(long size) {
                        seenNull = false;
                        lastSeen = null;
                        downstream.begin(-1);
                    }

                    @Override
                    public void end() {
                        seenNull = false;
                        lastSeen = null;
                        downstream.end();
                    }

                    @Override
                    public void accept(T t) {
                        if (t == null) {
                            if (!seenNull) {
                                seenNull = true;
                                downstream.accept(lastSeen = null);
                            }
                        } else if (lastSeen == null || !t.equals(lastSeen)) {
                            downstream.accept(lastSeen = t);
                        }
                    }
                };
            } else {
                return new Sink.ChainedReference<T, T>(sink) {

                    Set<T> seen;

                    @Override
                    public void begin(long size) {
                        seen = new HashSet<>();
                        downstream.begin(-1);
                    }

                    @Override
                    public void end() {
                        seen = null;
                        downstream.end();
                    }

                    @Override
                    public void accept(T t) {
                        if (!seen.contains(t)) {
                            seen.add(t);
                            downstream.accept(t);
                        }
                    }
                };
            }
        }
    };
}
Also used : LinkedHashSet(java.util.LinkedHashSet) HashSet(java.util.HashSet) Objects(java.util.Objects) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Set(java.util.Set) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) Spliterator(java.util.Spliterator) LinkedHashSet(java.util.LinkedHashSet) IntFunction(java.util.function.IntFunction) HashSet(java.util.HashSet) Set(java.util.Set) LinkedHashSet(java.util.LinkedHashSet) AtomicBoolean(java.util.concurrent.atomic.AtomicBoolean) IntFunction(java.util.function.IntFunction) ConcurrentHashMap(java.util.concurrent.ConcurrentHashMap) Spliterator(java.util.Spliterator) HashSet(java.util.HashSet) LinkedHashSet(java.util.LinkedHashSet)

Example 50 with Spliterator

use of java.util.Spliterator in project Bytecoder by mirkosertic.

the class LongPipeline method forEachWithCancel.

@Override
final boolean forEachWithCancel(Spliterator<Long> spliterator, Sink<Long> sink) {
    Spliterator.OfLong spl = adapt(spliterator);
    LongConsumer adaptedSink = adapt(sink);
    boolean cancelled;
    do {
    } while (!(cancelled = sink.cancellationRequested()) && spl.tryAdvance(adaptedSink));
    return cancelled;
}
Also used : LongConsumer(java.util.function.LongConsumer) ObjLongConsumer(java.util.function.ObjLongConsumer) Spliterator(java.util.Spliterator)

Aggregations

Spliterator (java.util.Spliterator)124 List (java.util.List)47 ArrayList (java.util.ArrayList)41 HashSet (java.util.HashSet)36 IntConsumer (java.util.function.IntConsumer)35 Set (java.util.Set)31 Objects (java.util.Objects)25 Collectors (java.util.stream.Collectors)25 Spliterators (java.util.Spliterators)24 Function (java.util.function.Function)24 Iterator (java.util.Iterator)23 Consumer (java.util.function.Consumer)23 Stream (java.util.stream.Stream)23 Map (java.util.Map)22 Arrays (java.util.Arrays)20 LongConsumer (java.util.function.LongConsumer)20 Collections (java.util.Collections)19 StreamSupport (java.util.stream.StreamSupport)19 Comparator (java.util.Comparator)18 Test (org.junit.Test)18