Example usage for java.util Iterator Iterator

List of usage examples for java.util Iterator Iterator

Introduction

In this page you can find the example usage for java.util Iterator Iterator.

Prototype

Iterator

Source Link

Usage

From source file:SortedMultiSet.java

public Iterator<Type> iterator() {
    return new Iterator<Type>() {
        int idx = 0;

        public boolean hasNext() {
            return idx < size;
        }/*from  ww  w  . j a  v  a2s .c o m*/

        public Type next() {
            if (hasNext()) {
                return field[idx++];
            }
            throw new NoSuchElementException();
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }

    };
}

From source file:ListOrderedMap.java

public Set keySet() {
    return new AbstractSet() {
        public int size() {
            return map.size();
        }/*from ww  w  .  j a  v a  2s  .  com*/

        public boolean contains(Object value) {
            return map.containsKey(value);
        }

        public void clear() {
            ListOrderedMap.this.clear();
        }

        public Iterator iterator() {
            return new Iterator() {
                Object last = null;
                Iterator keys = lst.iterator();

                public Object next() {
                    return last = keys.next();
                }

                public boolean hasNext() {
                    return keys.hasNext();
                }

                public void remove() {
                    keys.remove();
                    map.remove(last);
                }
            };
        }
    };
}

From source file:org.apache.openjpa.lib.util.concurrent.NullSafeConcurrentHashMap.java

/**
 * The returned data structure should not be shared among multiple
 * threads.//  ww  w. j a v  a 2 s .c  o  m
 */
public Iterator<Entry> randomEntryIterator() {
    return new Iterator<Entry>() {

        Iterator randomIter = randomKeys.iterator();
        Iterator nonRandomIter = NullSafeConcurrentHashMap.super.keySet().iterator();

        Set returned = new HashSet();
        Entry next;
        boolean nextSet = false;

        public boolean hasNext() {
            // we've set the next value and we haven't returned it yet
            if (nextSet)
                return true;

            // compute the next value. If the computation returns null,
            // return false. Else, store the next value and return true.
            Object nextKey;
            Object nextValue;
            if (randomIter.hasNext()) {
                nextKey = randomIter.next();
                nextValue = NullSafeConcurrentHashMap.super.get(nextKey);
                if (nextValue != null) {
                    returned.add(nextKey);
                    next = new EntryImpl(unmaskNull(nextKey), unmaskNull(nextValue));
                    nextSet = true;
                    return true;
                }
            }

            while (nonRandomIter.hasNext()) {
                nextKey = nonRandomIter.next();

                if (returned.contains(nextKey))
                    continue;

                nextValue = NullSafeConcurrentHashMap.super.get(nextKey);
                if (nextValue != null) {
                    returned.add(nextKey);
                    next = new EntryImpl(unmaskNull(nextKey), unmaskNull(nextValue));
                    nextSet = true;
                    return true;
                }
            }
            return false;
        }

        public Entry next() {
            // hasNext() will initialize this.next
            if (!nextSet && !hasNext())
                return null;

            // if we get here, then we're about to return a next value
            nextSet = false;

            if (containsKey(next.getKey()))
                return next;

            // something has changed since the last iteration (presumably
            // due to multi-threaded access to the underlying data
            // structure); recurse
            return next();
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:org.apache.sling.nosql.couchbase.resourceprovider.impl.CouchbaseNoSqlAdapter.java

@Override
public Iterator<NoSqlData> getChildren(String parentPath) {
    Bucket bucket = couchbaseClient.getBucket();
    // fetch all direct children of this path
    N1qlQuery query = N1qlQuery.simple(//from  w ww  .ja v a  2s  .co m
            select("*").from(couchbaseClient.getBucketName()).where(x(PN_PARENT_PATH).eq(s(parentPath))),
            N1QL_PARAMS);
    N1qlQueryResult queryResult = bucket.query(query);
    handleQueryError(queryResult);
    final Iterator<N1qlQueryRow> results = queryResult.iterator();
    return new Iterator<NoSqlData>() {
        @Override
        public boolean hasNext() {
            return results.hasNext();
        }

        @Override
        public NoSqlData next() {
            JsonObject item = results.next().value();
            JsonObject envelope = item.getObject(couchbaseClient.getBucketName());
            String path = envelope.getString(PN_PATH);
            JsonObject data = envelope.getObject(PN_DATA);
            return new NoSqlData(path, data.toMap(), MultiValueMode.LISTS);
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:io.gravitee.repository.redis.ratelimit.RedisRateLimitRepository.java

@Override
public Iterator<RateLimit> findAsyncAfter(long timestamp) {
    final List<List<String>> rateLimits = redisTemplate.execute(rateLimitAsyncScript,
            Collections.singletonList("after"), Long.toString(timestamp));
    final Iterator<List<String>> iterator = rateLimits.iterator();

    return new Iterator<RateLimit>() {
        @Override/*from w w  w .  ja va  2s.  c  om*/
        public boolean hasNext() {
            return iterator.hasNext();
        }

        @Override
        public RateLimit next() {
            List<String> lstRateLimit = iterator.next();
            Iterator<String> innerIterator = lstRateLimit.iterator();
            RateLimit rateLimit = new RateLimit(innerIterator.next());
            rateLimit.setAsync(Boolean.parseBoolean(innerIterator.next()));
            rateLimit.setUpdatedAt(Long.parseLong(innerIterator.next()));
            rateLimit.setCreatedAt(Long.parseLong(innerIterator.next()));
            rateLimit.setCounter(Long.parseLong(innerIterator.next()));
            rateLimit.setResetTime(Long.parseLong(innerIterator.next()));
            rateLimit.setLastRequest(Long.parseLong(innerIterator.next()));

            return rateLimit;
        }
    };
}

From source file:io.gravitee.repository.mongodb.ratelimit.MongoRateLimitRepository.java

@Override
public Iterator<RateLimit> findAsyncAfter(long timestamp) {
    DBObject query = BasicDBObjectBuilder.start(FIELD_ASYNC, true)
            .add(FIELD_UPDATED_AT, BasicDBObjectBuilder.start("$gte", timestamp).get()).get();

    final Iterator<DBObject> dbObjects = mongoOperations.getCollection(RATE_LIMIT_COLLECTION).find(query)
            .iterator();/*  ww w  .java2s . c om*/

    return new Iterator<RateLimit>() {

        @Override
        public boolean hasNext() {
            return dbObjects.hasNext();
        }

        @Override
        public RateLimit next() {
            DBObject dbObject = dbObjects.next();
            RateLimit rateLimit = new RateLimit((String) dbObject.get(FIELD_KEY));
            rateLimit.setCounter((long) dbObject.get(FIELD_COUNTER));
            rateLimit.setLastRequest((long) dbObject.get(FIELD_LAST_REQUEST));
            rateLimit.setResetTime(((Date) dbObject.get(FIELD_RESET_TIME)).getTime());
            rateLimit.setUpdatedAt((long) dbObject.get(FIELD_UPDATED_AT));
            rateLimit.setCreatedAt((long) dbObject.get(FIELD_CREATED_AT));
            rateLimit.setAsync((boolean) dbObject.get(FIELD_ASYNC));
            return rateLimit;
        }
    };
}

From source file:org.apache.tez.runtime.library.common.ValuesIterator.java

public Iterable<VALUE> getValues() {
    return new Iterable<VALUE>() {

        @Override/*w w w .  j  a v a 2  s  .  c  o  m*/
        public Iterator<VALUE> iterator() {

            return new Iterator<VALUE>() {

                private final int keyNumber = keyCtr;

                @Override
                public boolean hasNext() {
                    return hasMoreValues;
                }

                @Override
                public VALUE next() {
                    if (!hasMoreValues) {
                        throw new NoSuchElementException("iterate past last value");
                    }
                    Preconditions.checkState(keyNumber == keyCtr,
                            "Cannot use values iterator on the previous K-V pair after moveToNext has been invoked to move to the next K-V pair");

                    try {
                        readNextValue();
                        readNextKey();
                    } catch (IOException ie) {
                        throw new RuntimeException("problem advancing post rec#" + keyCtr, ie);
                    }
                    inputValueCounter.increment(1);
                    return value;
                }

                @Override
                public void remove() {
                    throw new UnsupportedOperationException("Cannot remove elements");
                }
            };
        }
    };
}

From source file:org.apache.sling.jcr.resource.internal.helper.jcr.BasicQueryLanguageProvider.java

@Override
public Iterator<ValueMap> queryResources(final ResolveContext<JcrProviderState> ctx, final String query,
        final String language) {
    final String queryLanguage = ArrayUtils.contains(getSupportedLanguages(ctx), language) ? language
            : DEFAULT_QUERY_LANGUAGE;//from  w w  w  .  j a  v a 2 s . c  om

    try {
        final QueryResult result = JcrResourceUtil.query(ctx.getProviderState().getSession(), query,
                queryLanguage);
        final String[] colNames = result.getColumnNames();
        final RowIterator rows = result.getRows();

        return new Iterator<ValueMap>() {

            private ValueMap next;

            {
                next = seek();
            }

            @Override
            public boolean hasNext() {
                return next != null;
            };

            @Override
            public ValueMap next() {
                if (next == null) {
                    throw new NoSuchElementException();
                }
                final ValueMap result = next;
                next = seek();
                return result;
            }

            private ValueMap seek() {
                ValueMap result = null;
                while (result == null && rows.hasNext()) {
                    try {
                        final Row jcrRow = rows.nextRow();
                        final String resourcePath = ctx.getProviderState().getHelperData().pathMapper
                                .mapJCRPathToResourcePath(jcrRow.getPath());
                        if (resourcePath != null
                                && providerContext.getExcludedPaths().matches(resourcePath) == null) {
                            final Map<String, Object> row = new HashMap<String, Object>();

                            boolean didPath = false;
                            boolean didScore = false;
                            final Value[] values = jcrRow.getValues();
                            for (int i = 0; i < values.length; i++) {
                                Value v = values[i];
                                if (v != null) {
                                    String colName = colNames[i];
                                    row.put(colName, JcrResourceUtil.toJavaObject(values[i]));
                                    if (colName.equals(QUERY_COLUMN_PATH)) {
                                        didPath = true;
                                        row.put(colName, ctx.getProviderState().getHelperData().pathMapper
                                                .mapJCRPathToResourcePath(
                                                        JcrResourceUtil.toJavaObject(values[i]).toString()));
                                    }
                                    if (colName.equals(QUERY_COLUMN_SCORE)) {
                                        didScore = true;
                                    }
                                }
                            }
                            if (!didPath) {
                                row.put(QUERY_COLUMN_PATH, ctx.getProviderState().getHelperData().pathMapper
                                        .mapJCRPathToResourcePath(jcrRow.getPath()));
                            }
                            if (!didScore) {
                                row.put(QUERY_COLUMN_SCORE, jcrRow.getScore());
                            }
                            result = new ValueMapDecorator(row);
                        }
                    } catch (final RepositoryException re) {
                        logger.error("queryResources$next: Problem accessing row values", re);
                    }
                }
                return result;
            }

            @Override
            public void remove() {
                throw new UnsupportedOperationException("remove");
            }
        };
    } catch (final javax.jcr.query.InvalidQueryException iqe) {
        throw new QuerySyntaxException(iqe.getMessage(), query, language, iqe);
    } catch (final RepositoryException re) {
        throw new SlingException(re.getMessage(), re);
    }

}

From source file:org.jcurl.core.impl.CurveStoreImpl.java

public Iterator<Iterable<Entry<Double, R1RNFunction>>> iterator() {
    return new Iterator<Iterable<Entry<Double, R1RNFunction>>>() {
        int current = 0;

        public boolean hasNext() {
            return current < curve.length;
        }//  ww w . j  av  a 2 s.  c  o m

        public Iterable<Entry<Double, R1RNFunction>> next() {
            return curve[current++];
        }

        public void remove() {
            throw new UnsupportedOperationException();
        }
    };
}

From source file:com.blacklocus.metrics.DemuxedKey.java

@Override
public Iterator<Iterable<T>> iterator() {
    return new Iterator<Iterable<T>>() {

        int permutation = permutable ? 2 : 1;
        Iterator<Iterable<T>> nextSegmentIt = nextSegment == null ? null : nextSegment.iterator();

        @Override/*from   w  ww . j a  v a2 s  .  co m*/
        public boolean hasNext() {
            boolean isTail = nextSegmentIt == null;
            if (isTail) {
                return permutation > 0;
            } else {
                return permutation > 0 && nextSegmentIt != null && nextSegmentIt.hasNext();
            }
        }

        @Override
        public Iterable<T> next() {
            assert permutation > 0 && permutation <= 2;
            boolean isTail = nextSegmentIt == null;
            if (isTail) {
                if (permutation == 2) {
                    permutation = 1;
                    return Collections.emptyList();
                } else {
                    assert permutation == 1;
                    permutation = 0;
                    return ImmutableList.of(token);
                }
            } else {
                if (permutation == 2) {
                    Iterable<T> next = nextSegmentIt.next();
                    if (!nextSegmentIt.hasNext()) {
                        permutation = 1;
                        nextSegmentIt = nextSegment.iterator();
                    }
                    return next;
                } else {
                    assert permutation == 1;
                    Iterable<T> next = Iterables.concat(ImmutableList.of(token), nextSegmentIt.next());
                    if (!nextSegmentIt.hasNext()) {
                        permutation = 0;
                        nextSegmentIt = null;
                    }
                    return next;
                }
            }
        }

        @Override
        public void remove() {
            throw new UnsupportedOperationException("Nope.");
        }
    };
}