List of usage examples for com.google.common.collect PeekingIterator next
@Override E next();
The objects returned by consecutive calls to #peek() then #next() are guaranteed to be equal to each other.
From source file:com.indeed.lsmtree.core.MergingIterator.java
@Override protected Generation.Entry<K, V> computeNext() { if (heap.isEmpty()) { return endOfData(); }/* w w w .j a v a2s.c o m*/ PeekingIterator<EntryAndGenerationId<K, V>> first = heap.poll(); EntryAndGenerationId<K, V> ret = first.next(); if (first.hasNext()) { temp.add(first); } while (!heap.isEmpty() && keyComparator.compare(ret.entry.getKey(), heap.peek().peek().entry.getKey()) == 0) { PeekingIterator<EntryAndGenerationId<K, V>> iter = heap.poll(); iter.next(); if (iter.hasNext()) { temp.add(iter); } } heap.addAll(temp); temp.clear(); return ret.entry; }
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 va 2 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:com.google.errorprone.bugpatterns.FallThrough.java
@Override public Description matchSwitch(SwitchTree tree, VisitorState state) { PeekingIterator<JCTree.JCCase> it = Iterators.peekingIterator(((JCTree.JCSwitch) tree).cases.iterator()); while (it.hasNext()) { JCTree.JCCase caseTree = it.next(); if (!it.hasNext()) { break; }/* w w w .j a v a 2s. com*/ JCTree.JCCase next = it.peek(); if (caseTree.stats.isEmpty()) { continue; } // We only care whether the last statement completes; javac would have already // reported an error if that statement wasn't reachable, and the answer is // independent of any preceding statements. boolean completes = Reachability.canCompleteNormally(getLast(caseTree.stats)); String comments = state.getSourceCode() .subSequence(caseEndPosition(state, caseTree), next.getStartPosition()).toString().trim(); if (completes && !FALL_THROUGH_PATTERN.matcher(comments).find()) { state.reportMatch(buildDescription(next).setMessage( "Switch case may fall through; add a `// fall through` comment if it was" + " deliberate") .build()); } else if (!completes && FALL_THROUGH_PATTERN.matcher(comments).find()) { state.reportMatch(buildDescription(next) .setMessage("Switch case has 'fall through' comment, but does not fall through").build()); } } return NO_MATCH; }
From source file:com.metamx.druid.indexer.granularity.ArbitraryGranularitySpec.java
@JsonCreator public ArbitraryGranularitySpec(@JsonProperty("intervals") List<Interval> inputIntervals) { intervals = Sets.newTreeSet(Comparators.intervalsByStartThenEnd()); // Insert all intervals for (final Interval inputInterval : inputIntervals) { intervals.add(inputInterval);// www .j a va2 s. co m } // 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 IllegalArgumentException( String.format("Overlapping intervals: %s, %s", currentInterval, nextInterval)); } } } }
From source file:com.google.errorprone.bugpatterns.MultiVariableDeclaration.java
private Description checkDeclarations(List<? extends Tree> children, VisitorState state) { PeekingIterator<Tree> it = Iterators.<Tree>peekingIterator(children.iterator()); while (it.hasNext()) { if (it.peek().getKind() != Tree.Kind.VARIABLE) { it.next(); continue; }//from w w w.j a va 2 s. c o m VariableTree variableTree = (VariableTree) it.next(); ArrayList<VariableTree> fragments = new ArrayList<>(); fragments.add(variableTree); // Javac handles multi-variable declarations by lowering them in the parser into a series of // individual declarations, all of which have the same start position. We search for the first // declaration in the group, which is either the first variable declared in this scope or has // a distinct end position from the previous declaration. while (it.hasNext() && it.peek().getKind() == Tree.Kind.VARIABLE && ((JCTree) variableTree).getStartPosition() == ((JCTree) it.peek()).getStartPosition()) { fragments.add((VariableTree) it.next()); } if (fragments.size() == 1) { continue; } Fix fix = SuggestedFix.replace(((JCTree) fragments.get(0)).getStartPosition(), state.getEndPosition(Iterables.getLast(fragments)), Joiner.on("; ").join(fragments) + ";"); state.reportMatch(describeMatch(fragments.get(0), fix)); } return NO_MATCH; }
From source file:is.illuminati.block.spyros.garmin.model.Lap.java
/** * Get a list of all pauses in the lap.// ww w .j ava 2s.c om * @return list of all pauses. */ public ImmutableList<Pause> getPauses() { ImmutableList.Builder<Pause> pausesBuilder = ImmutableList.builder(); PeekingIterator<Track> it = Iterators.peekingIterator(tracks.iterator()); while (it.hasNext()) { Track former = it.next(); Track latter; if (it.hasNext()) { latter = it.peek(); } else { break; } Duration gap = new Duration(former.getEndTime(), latter.getStartTime()); if (gap.isLongerThan(Duration.standardSeconds(10))) { pausesBuilder.add(new Pause(former.getEndTime(), latter.getStartTime())); } } return pausesBuilder.build(); }
From source file:org.apache.kylin.storage.gtrecord.SortMergedPartitionResultIterator.java
@Override public GTRecord next() { if (!hasNext()) { throw new NoSuchElementException(); }//w ww. j av a 2s. c om // get smallest record PeekingIterator<GTRecord> it = heap.poll(); // WATCH OUT! record got from PartitionResultIterator.next() may changed later, // so we must make a shallow copy of it. record.shallowCopyFrom(it.next()); if (it.hasNext()) { heap.offer(it); } return record; }
From source file:com.palantir.atlasdb.keyvalue.impl.Cells.java
/** * The Collection provided to this function has to be sorted and strictly increasing. *///w w w . j a v a 2 s . c o m public static <T> Iterator<RowResult<T>> createRowView(final Collection<Map.Entry<Cell, T>> sortedIterator) { final PeekingIterator<Entry<Cell, T>> it = Iterators.peekingIterator(sortedIterator.iterator()); Iterator<Map.Entry<byte[], SortedMap<byte[], T>>> resultIt = new AbstractIterator<Map.Entry<byte[], SortedMap<byte[], T>>>() { byte[] row = null; SortedMap<byte[], T> map = null; @Override protected Entry<byte[], SortedMap<byte[], T>> computeNext() { if (!it.hasNext()) { return endOfData(); } row = it.peek().getKey().getRowName(); ImmutableSortedMap.Builder<byte[], T> mapBuilder = ImmutableSortedMap .orderedBy(UnsignedBytes.lexicographicalComparator()); while (it.hasNext()) { Entry<Cell, T> peek = it.peek(); if (!Arrays.equals(peek.getKey().getRowName(), row)) { break; } mapBuilder.put(peek.getKey().getColumnName(), peek.getValue()); it.next(); } map = mapBuilder.build(); return Maps.immutableEntry(row, map); } }; return RowResults.viewOfEntries(resultIt); }
From source file:org.locationtech.geogig.plumbing.merge.CheckMergeScenarioOp.java
/** * Get all the next set of nodes from the iterator with the same path. * //from w w w. jav a2 s .co m * @param iterator * @return */ private List<DiffEntry> nextPath(PeekingIterator<DiffEntry> iterator) { List<DiffEntry> entries = new ArrayList<DiffEntry>(); DiffEntry next = iterator.next(); entries.add(next); String name = next.oldName() != null ? next.oldName() : next.newName(); while (iterator.hasNext()) { DiffEntry peeked = iterator.peek(); String peekedName = peeked.oldName() != null ? peeked.oldName() : peeked.newName(); if (name.equals(peekedName)) { entries.add(iterator.next()); } else { break; } } return entries; }
From source file:org.renjin.eval.Calls.java
/** * Argument matching is done by a three-pass process: * <ol>// w ww .j a v a2s. c o m * <li><strong>Exact matching on tags.</strong> For each named supplied argument the list of formal arguments * is searched for an item whose name matches exactly. It is an error to have the same formal * argument match several actuals or vice versa.</li> * * <li><strong>Partial matching on tags.</strong> Each remaining named supplied argument is compared to the * remaining formal arguments using partial matching. If the name of the supplied argument * matches exactly with the first part of a formal argument then the two arguments are considered * to be matched. It is an error to have multiple partial matches. * Notice that if f <- function(fumble, fooey) fbody, then f(f = 1, fo = 2) is illegal, * even though the 2nd actual argument only matches fooey. f(f = 1, fooey = 2) is legal * though since the second argument matches exactly and is removed from consideration for * partial matching. If the formal arguments contain ... then partial matching is only applied to * arguments that precede it. * * <li><strong>Positional matching.</strong> Any unmatched formal arguments are bound to unnamed supplied arguments, * in order. If there is a ... argument, it will take up the remaining arguments, tagged or not. * If any arguments remain unmatched an error is declared. * * @param actuals the actual arguments supplied to the list * @param populateMissing */ public static PairList matchArguments(PairList formals, PairList actuals, boolean populateMissing) { PairList.Builder result = new PairList.Builder(); List<PairList.Node> unmatchedActuals = Lists.newArrayList(); for (PairList.Node argNode : actuals.nodes()) { unmatchedActuals.add(argNode); } List<PairList.Node> unmatchedFormals = Lists.newArrayList(formals.nodes()); // do exact matching for (ListIterator<PairList.Node> formalIt = unmatchedFormals.listIterator(); formalIt.hasNext();) { PairList.Node formal = formalIt.next(); if (formal.hasTag()) { Symbol name = formal.getTag(); Collection<PairList.Node> matches = Collections2.filter(unmatchedActuals, PairList.Predicates.matches(name)); if (matches.size() == 1) { PairList.Node match = first(matches); result.add(name, match.getValue()); formalIt.remove(); unmatchedActuals.remove(match); } else if (matches.size() > 1) { throw new EvalException( String.format("Multiple named values provided for argument '%s'", name.getPrintName())); } } } // do partial matching Collection<PairList.Node> remainingNamedFormals = filter(unmatchedFormals, PairList.Predicates.hasTag()); for (Iterator<PairList.Node> actualIt = unmatchedActuals.iterator(); actualIt.hasNext();) { PairList.Node actual = actualIt.next(); if (actual.hasTag()) { Collection<PairList.Node> matches = Collections2.filter(remainingNamedFormals, PairList.Predicates.startsWith(actual.getTag())); if (matches.size() == 1) { PairList.Node match = first(matches); result.add(match.getTag(), actual.getValue()); actualIt.remove(); unmatchedFormals.remove(match); } else if (matches.size() > 1) { throw new EvalException( String.format("Provided argument '%s' matches multiple named formal arguments: %s", actual.getTag().getPrintName(), argumentTagList(matches))); } } } // match any unnamed args positionally Iterator<PairList.Node> formalIt = unmatchedFormals.iterator(); PeekingIterator<PairList.Node> actualIt = Iterators.peekingIterator(unmatchedActuals.iterator()); while (formalIt.hasNext()) { PairList.Node formal = formalIt.next(); if (Symbols.ELLIPSES.equals(formal.getTag())) { PromisePairList.Builder promises = new PromisePairList.Builder(); while (actualIt.hasNext()) { PairList.Node actual = actualIt.next(); promises.add(actual.getRawTag(), actual.getValue()); } result.add(formal.getTag(), promises.build()); } else if (hasNextUnTagged(actualIt)) { result.add(formal.getTag(), nextUnTagged(actualIt).getValue()); } else if (populateMissing) { result.add(formal.getTag(), Symbol.MISSING_ARG); } } if (actualIt.hasNext()) { throw new EvalException(String.format("Unmatched positional arguments")); } return result.build(); }