Example usage for com.google.common.collect Iterators peekingIterator

List of usage examples for com.google.common.collect Iterators peekingIterator

Introduction

In this page you can find the example usage for com.google.common.collect Iterators peekingIterator.

Prototype

@Deprecated
public static <T> PeekingIterator<T> peekingIterator(PeekingIterator<T> iterator) 

Source Link

Document

Simply returns its argument.

Usage

From source file:com.indeed.lsmtree.core.MergingIterator.java

public MergingIterator(final Collection<Iterator<Generation.Entry<K, V>>> iterators,
        final Comparator<K> keyComparator) {
    this.keyComparator = keyComparator;
    Comparator<PeekingIterator<EntryAndGenerationId<K, V>>> comparator = new Comparator<PeekingIterator<EntryAndGenerationId<K, V>>>() {
        @Override/*ww w.ja v a2s . c  o  m*/
        public int compare(PeekingIterator<EntryAndGenerationId<K, V>> o1,
                PeekingIterator<EntryAndGenerationId<K, V>> o2) {
            EntryAndGenerationId<K, V> a = o1.peek();
            EntryAndGenerationId<K, V> b = o2.peek();
            int cmp = keyComparator.compare(a.entry.getKey(), b.entry.getKey());
            if (cmp != 0)
                return cmp;
            return Ints.compare(a.generationId, b.generationId);
        }
    };
    heap = new PriorityQueue<PeekingIterator<EntryAndGenerationId<K, V>>>(iterators.size(), comparator);
    int i = 0;
    for (final Iterator<Generation.Entry<K, V>> iterator : iterators) {
        final int generationId = i;
        PeekingIterator<EntryAndGenerationId<K, V>> iter = Iterators
                .peekingIterator(new Iterator<EntryAndGenerationId<K, V>>() {

                    Iterator<Generation.Entry<K, V>> it = iterator;

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

                    @Override
                    public EntryAndGenerationId<K, V> next() {
                        return new EntryAndGenerationId<K, V>(it.next(), generationId);
                    }

                    @Override
                    public void remove() {
                        throw new UnsupportedOperationException();
                    }
                });
        if (iter.hasNext()) {
            heap.add(iter);
        }
        i++;
    }
}

From source file:edu.byu.nlp.al.NDeepInstanceManager.java

@VisibleForTesting
public NDeepInstanceManager(RandomRoundRobinQueue<FlatInstance<D, L>> q,
        AnnotationRecorder<D, L> annotationRecorder) {
    super(annotationRecorder);
    this.it = Iterators.peekingIterator(q.iterator());
    this.q = q;/* ww  w.j ava2s .  c o m*/
}

From source file:co.cask.cdap.metrics.query.MetricStoreRequestExecutor.java

public JsonElement executeQuery(MetricDataQuery query) throws Exception {
    // Pretty ugly logic now. Need to refactor
    Object resultObj;//  w  ww  . j  a v  a 2  s  .co m
    if (query.getResolution() != Integer.MAX_VALUE) {
        TimeSeriesResponse.Builder builder = TimeSeriesResponse.builder(query.getStartTs(), query.getEndTs());
        // Special metrics handle that requires computation from multiple time series.
        if (query.getMetrics().containsKey("system.process.busyness")) {
            computeProcessBusyness(query, builder);
        } else {
            PeekingIterator<TimeValue> timeValueItor = Iterators.peekingIterator(queryTimeSeries(query));

            long resultTimeStamp = (query.getStartTs() / query.getResolution()) * query.getResolution();

            for (int i = 0; i < query.getLimit(); i++) {
                if (timeValueItor.hasNext() && timeValueItor.peek().getTimestamp() == resultTimeStamp) {
                    builder.addData(resultTimeStamp, timeValueItor.next().getValue());
                } else {
                    // If the scan result doesn't have value for a timestamp, we add 0 to the result-returned for that timestamp
                    builder.addData(resultTimeStamp, 0);
                }
                resultTimeStamp += query.getResolution();
            }
        }
        resultObj = builder.build();

    } else {
        // Special metrics handle that requires computation from multiple aggregates results.
        if (query.getMetrics().containsKey("system.process.events.pending")) {
            resultObj = computeFlowletPending(query);
        } else {
            resultObj = getAggregates(query);
        }
    }

    return GSON.toJsonTree(resultObj);
}

From source file:org.apache.druid.segment.indexing.granularity.ArbitraryGranularitySpec.java

@JsonCreator
public ArbitraryGranularitySpec(@JsonProperty("queryGranularity") Granularity queryGranularity,
        @JsonProperty("rollup") Boolean rollup, @JsonProperty("intervals") List<Interval> inputIntervals) {
    this.queryGranularity = queryGranularity == null ? Granularities.NONE : queryGranularity;
    this.rollup = rollup == null ? Boolean.TRUE : rollup;
    this.intervals = Sets.newTreeSet(Comparators.intervalsByStartThenEnd());

    if (inputIntervals == null) {
        inputIntervals = Lists.newArrayList();
    }/*from   ww  w . j  ava 2  s.co  m*/

    // Insert all intervals
    for (final Interval inputInterval : inputIntervals) {
        intervals.add(inputInterval);
    }

    // Ensure intervals are non-overlapping (but they may abut each other)
    final PeekingIterator<Interval> intervalIterator = Iterators.peekingIterator(intervals.iterator());
    while (intervalIterator.hasNext()) {
        final Interval currentInterval = intervalIterator.next();

        if (intervalIterator.hasNext()) {
            final Interval nextInterval = intervalIterator.peek();
            if (currentInterval.overlaps(nextInterval)) {
                throw new IAE("Overlapping intervals: %s, %s", currentInterval, nextInterval);
            }
        }
    }
}

From source file:co.cask.cdap.data.file.PartitionedFileWriter.java

@Override
public void appendAll(final Iterator<? extends T> events) throws IOException {
    if (closed) {
        throw new IOException("Attempts to write to a closed FileWriter.");
    }//from  w  ww . j av  a2s .  com

    PeekingIterator<T> iterator = Iterators.peekingIterator(events);
    while (iterator.hasNext()) {
        getWriter(iterator.peek()).appendAll(new AppendIterator(iterator));
    }
}

From source file:com.metamx.druid.collect.OrderedMergeIterator.java

public OrderedMergeIterator(final Comparator<T> comparator, Iterator<Iterator<T>> iterators) {
    this.comparator = comparator;
    pQueue = new PriorityQueue<PeekingIterator<T>>(16, new Comparator<PeekingIterator<T>>() {
        @Override//w  ww  .  j  av a  2s.c o m
        public int compare(PeekingIterator<T> lhs, PeekingIterator<T> rhs) {
            return comparator.compare(lhs.peek(), rhs.peek());
        }
    });

    iterOfIterators = Iterators
            .peekingIterator(FunctionalIterator.create(iterators).filter(new Predicate<Iterator<T>>() {
                @Override
                public boolean apply(@Nullable Iterator<T> input) {
                    return input.hasNext();
                }
            }).transform(new Function<Iterator<T>, PeekingIterator<T>>() {
                @Override
                public PeekingIterator<T> apply(@Nullable Iterator<T> input) {
                    return Iterators.peekingIterator(input);
                }
            }));
}

From source file:eu.lp0.cursus.scoring.scores.impl.TopCountryOverallPositionData.java

@Override
protected LinkedListMultimap<Integer, Pilot> calculateOverallPositionsWithOrder() {
    if (scores.getRaces().size() < 2) {
        return super.calculateOverallPositionsWithOrder();
    }/*from w w w  .j a va2  s  .c  o  m*/

    Comparator<Pilot> averagePoints = new AveragePointsComparator<T>(scores, placingMethod);
    Comparator<Pilot> racePlacings = new PilotRacePlacingComparator<T>(scores, placingMethod);
    Comparator<Pilot> fallbackOrdering = new PilotRaceNumberComparator();
    SortedSet<Pilot> pilots = new TreeSet<Pilot>(
            Ordering.from(averagePoints).compound(racePlacings).compound(fallbackOrdering));
    pilots.addAll(scores.getPilots());

    LinkedListMultimap<Integer, Pilot> overallPositions = LinkedListMultimap.create();
    List<Pilot> collectedPilots = new ArrayList<Pilot>(scores.getPilots().size());
    int position = 1;

    PeekingIterator<Pilot> it = Iterators.peekingIterator(pilots.iterator());
    while (it.hasNext()) {
        Pilot pilot = it.next();
        collectedPilots.add(pilot);

        // If this pilot compares equally with the next pilot, add them too
        while (it.hasNext() && racePlacings.compare(it.peek(), pilot) == 0) {
            collectedPilots.add(it.next());
        }

        // Sort them by an arbitrary order
        Collections.sort(collectedPilots, fallbackOrdering);

        // Add them all to this position
        overallPositions.putAll(position, collectedPilots);
        position += collectedPilots.size();

        collectedPilots.clear();
    }

    return overallPositions;
}

From source file:org.apache.druid.collections.OrderedMergeIterator.java

public OrderedMergeIterator(final Comparator<T> comparator, Iterator<Iterator<T>> iterators) {
    this.comparator = comparator;
    firstElementComparedPQueue = new PriorityQueue<PeekingIterator<T>>(16,
            new Comparator<PeekingIterator<T>>() {
                @Override/*from  w ww .j a  v  a2  s  .  com*/
                public int compare(PeekingIterator<T> lhs, PeekingIterator<T> rhs) {
                    return comparator.compare(lhs.peek(), rhs.peek());
                }
            });

    iterOfIterators = Iterators
            .peekingIterator(FunctionalIterator.create(iterators).filter(new Predicate<Iterator<T>>() {
                @Override
                public boolean apply(Iterator<T> input) {
                    return input.hasNext();
                }
            }).transform(new Function<Iterator<T>, PeekingIterator<T>>() {
                @Override
                public PeekingIterator<T> apply(Iterator<T> input) {
                    return Iterators.peekingIterator(input);
                }
            }));
}

From source file:fr.loria.parole.labelutils.Layer.java

/**
 * Construct an IntervalTier from this Layer. The first and last Marker times will determine the time domain of the
 * IntervalTier. <br>/*from   w w w  . j  a v  a  2 s. com*/
 * Note that the first Marker's label will be discarded, since its function will be reduced to providing the start time of the
 * first Interval.
 * 
 * @return the IntervalTier
 */
public IntervalTier toIntervalTier() {
    // temporarily store intervals in List
    List<Interval> intervals = Lists.newArrayList();

    // iterate over markers, stopping before the last one
    PeekingIterator<Marker> iterator = Iterators.peekingIterator(markers.iterator());
    while (iterator.hasNext()) {
        Marker startMarker = iterator.next();
        try {
            Marker endMarker = iterator.peek();
            Interval interval = new Interval(startMarker.getTime(), endMarker.getTime(), endMarker.getLabel());
            intervals.add(interval);
        } catch (NoSuchElementException e) {
            // this is already the last Marker
            break;
        }
    }

    // construct new IntervalTier
    IntervalTier tier = new IntervalTier(name, intervals);
    return tier;
}

From source file:com.google.errorprone.bugpatterns.AbstractExpectedExceptionChecker.java

@Override
public Description matchMethod(MethodTree tree, VisitorState state) {
    if (tree.getBody() == null) {
        return NO_MATCH;
    }//from w  ww  .  j av a2s.  com
    PeekingIterator<? extends StatementTree> it = Iterators
            .peekingIterator(tree.getBody().getStatements().iterator());
    while (it.hasNext() && !MATCHER.matches(it.peek(), state)) {
        it.next();
    }
    List<Tree> expectations = new ArrayList<>();
    while (it.hasNext() && MATCHER.matches(it.peek(), state)) {
        expectations.add(it.next());
    }
    if (expectations.isEmpty()) {
        return NO_MATCH;
    }
    List<StatementTree> suffix = new ArrayList<>();
    Iterators.addAll(suffix, it);
    return handleMatch(tree, state, expectations, suffix);
}