当前位置: 首页>>代码示例>>Java>>正文


Java PeekingIterator类代码示例

本文整理汇总了Java中com.google.common.collect.PeekingIterator的典型用法代码示例。如果您正苦于以下问题:Java PeekingIterator类的具体用法?Java PeekingIterator怎么用?Java PeekingIterator使用的例子?那么恭喜您, 这里精选的类代码示例或许可以为您提供帮助。


PeekingIterator类属于com.google.common.collect包,在下文中一共展示了PeekingIterator类的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: getNonOverlappingBounds

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
/**
 * Retrieves non-overlapping bounds for the list of input bounds
 *
 * Assume we have the following bounds
 * (brackets representing left/right bound):
 * [   ] [   ]    [   ]   [  ]
 * [   ]         [       ]
 * This method will return the following bounds:
 * [         ]    [          ]
 *
 * @param bounds unsorted bounds to find overlaps
 * @return the non-overlapping bounds
 */
public static <T extends RingPosition<T>> Set<Bounds<T>> getNonOverlappingBounds(Iterable<Bounds<T>> bounds)
{
    ArrayList<Bounds<T>> sortedBounds = Lists.newArrayList(bounds);
    Collections.sort(sortedBounds, new Comparator<Bounds<T>>()
    {
        public int compare(Bounds<T> o1, Bounds<T> o2)
        {
            return o1.left.compareTo(o2.left);
        }
    });

    Set<Bounds<T>> nonOverlappingBounds = Sets.newHashSet();

    PeekingIterator<Bounds<T>> it = Iterators.peekingIterator(sortedBounds.iterator());
    while (it.hasNext())
    {
        Bounds<T> beginBound = it.next();
        Bounds<T> endBound = beginBound;
        while (it.hasNext() && endBound.right.compareTo(it.peek().left) >= 0)
            endBound = it.next();
        nonOverlappingBounds.add(new Bounds<>(beginBound.left, endBound.right));
    }

    return nonOverlappingBounds;
}
 
开发者ID:Netflix,项目名称:sstable-adaptor,代码行数:39,代码来源:Bounds.java

示例2: visitStatements

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
private void visitStatements(List<? extends StatementTree> statements) {
    boolean first = true;
    PeekingIterator<StatementTree> it =
            Iterators.<StatementTree>peekingIterator(statements.iterator());
    dropEmptyDeclarations();
    while (it.hasNext()) {
        StatementTree tree = it.next();
        builder.forcedBreak();
        if (!first) {
            builder.blankLineWanted(BlankLineWanted.PRESERVE);
        }
        markForPartialFormat();
        first = false;
        List<VariableTree> fragments = variableFragments(it, tree);
        if (!fragments.isEmpty()) {
            visitVariables(
                    fragments,
                    DeclarationKind.NONE,
                    canLocalHaveHorizontalAnnotations(fragments.get(0).getModifiers()));
        } else {
            scan(tree, null);
        }
    }
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:25,代码来源:JavaInputAstVisitor.java

示例3: optionalizeSpacesAfterLinks

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
/**
 * Replaces whitespace after a {@code href=...>} token with an "optional link break." This allows
 * us to output either {@code <a href=foo>foo</a>} or {@code <a href=foo>\nfoo</a>}, depending on
 * how much space we have left on the line.
 * <p>
 * <p>This method must be called after {@link #joinAdjacentLiteralsAndAdjacentWhitespace}, as it
 * assumes that adjacent whitespace tokens have already been joined.
 */
private static ImmutableList<Token> optionalizeSpacesAfterLinks(List<Token> input) {
    ImmutableList.Builder<Token> output = ImmutableList.builder();

    for (PeekingIterator<Token> tokens = peekingIterator(input.iterator()); tokens.hasNext(); ) {
        if (tokens.peek().getType() == LITERAL && tokens.peek().getValue().matches("^href=[^>]*>")) {
            output.add(tokens.next());

            if (tokens.peek().getType() == WHITESPACE) {
                output.add(new Token(OPTIONAL_LINE_BREAK, tokens.next().getValue()));
            }
        } else {
            output.add(tokens.next());
        }
    }

    return output.build();

/*
 * Note: We do not want to insert <p> tags inside <pre>. Fortunately, the formatter gets that
 * right without special effort on our part. The reason: Line breaks inside a <pre> section are
 * of type FORCED_NEWLINE rather than WHITESPACE.
 */
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:32,代码来源:JavadocLexer.java

示例4: deindentPreCodeBlocks

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
/**
 * Adjust indentation inside `<pre>{@code` blocks.
 * <p>
 * <p>Also trim leading and trailing blank lines, and move the trailing `}` to its own line.
 */
private static ImmutableList<Token> deindentPreCodeBlocks(List<Token> input) {
    ImmutableList.Builder<Token> output = ImmutableList.builder();
    for (PeekingIterator<Token> tokens = peekingIterator(input.iterator()); tokens.hasNext(); ) {
        if (tokens.peek().getType() != PRE_OPEN_TAG) {
            output.add(tokens.next());
            continue;
        }

        output.add(tokens.next());
        List<Token> initialNewlines = new ArrayList<>();
        while (tokens.hasNext() && tokens.peek().getType() == FORCED_NEWLINE) {
            initialNewlines.add(tokens.next());
        }
        if (tokens.peek().getType() != LITERAL
                || !tokens.peek().getValue().matches("[ \t]*[{]@code")) {
            output.addAll(initialNewlines);
            output.add(tokens.next());
            continue;
        }

        deindentPreCodeBlock(output, tokens);
    }
    return output.build();
}
 
开发者ID:tranleduy2000,项目名称:javaide,代码行数:30,代码来源:JavadocLexer.java

示例5: nextTree

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
private InstanceParsePair<NlpFocus<DepNode, DepTree>> nextTree(PeekingIterator<NlpFocus<DepNode,
        DepTree>> iterator) {
    if (!iterator.hasNext()) {
        return null;
    }
    List<NlpFocus<DepNode, DepTree>> instances = new ArrayList<>();
    NlpFocus<DepNode, DepTree> current = iterator.next();
    DepTree tree = current.sequence();
    instances.add(current);
    while (iterator.hasNext()) {
        current = iterator.peek();
        if (tree.index() == current.sequence().index()) {
            instances.add(iterator.next());
            continue;
        }
        break;
    }
    return new InstanceParsePair<>(instances, (DefaultDepTree) tree);
}
 
开发者ID:clearwsd,项目名称:clearwsd,代码行数:20,代码来源:SemevalReader.java

示例6: toRanges

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
/**
 * Converts a set of integers into a set of contiguous closed ranges that equally represent the
 * input integers.
 * <p>
 * The resulting ranges will be in ascending order.
 * <p>
 * TODO(wfarner): Change this to return a canonicalized RangeSet.
 *
 * @param values Values to transform to ranges.
 * @return Closed ranges with identical members to the input set.
 */
public static Set<Range<Integer>> toRanges(Iterable<Integer> values) {
  ImmutableSet.Builder<Range<Integer>> builder = ImmutableSet.builder();

  PeekingIterator<Integer> iterator =
      Iterators.peekingIterator(Sets.newTreeSet(values).iterator());

  // Build ranges until there are no numbers left.
  while (iterator.hasNext()) {
    // Start a new range.
    int start = iterator.next();
    int end = start;
    // Increment the end until the range is non-contiguous.
    while (iterator.hasNext() && iterator.peek() == end + 1) {
      end++;
      iterator.next();
    }

    builder.add(Range.closed(start, end));
  }

  return builder.build();
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Mesos,代码行数:34,代码来源:Numbers.java

示例7: expectStateTransitions

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
private void expectStateTransitions(
    String taskId,
    ScheduleStatus initial,
    ScheduleStatus next,
    ScheduleStatus... others) {

  List<ScheduleStatus> statuses = ImmutableList.<ScheduleStatus>builder()
      .add(initial)
      .add(next)
      .add(others)
      .build();
  PeekingIterator<ScheduleStatus> it = Iterators.peekingIterator(statuses.iterator());
  while (it.hasNext()) {
    ScheduleStatus cur = it.next();
    try {
      eventSink.post(matchStateChange(taskId, cur, it.peek()));
    } catch (NoSuchElementException e) {
      // Expected.
    }
  }
}
 
开发者ID:PacktPublishing,项目名称:Mastering-Mesos,代码行数:22,代码来源:StateManagerImplTest.java

示例8: getPzxBlock

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
private static PZXBlock getPzxBlock(PeekingIterator<TapeBlock> iterator) {
    TapeBlock block = iterator.next();
    PulseList blockPulseList = block.getPulseList();
    PZXBlock pzxBlock = new PZXNullBlock();
    switch (block.getBlockType()) {
        case UNKNOWN:
            // TODO if this is the beginning of the tape and followed by a pilot discard
            // TODO if this is about a second after a data block with a tail but before a pulse block use a pause block?
            pzxBlock = new PZXPulseBlock(blockPulseList);
            break;
        case PILOT:
            pzxBlock = getPzxPulseBlock(iterator, blockPulseList);
            break;
        case SYNC_CANDIDATE:
            pzxBlock = new PZXPulseBlock(blockPulseList);
            break;
        case DATA:
            pzxBlock = getPzxDataBlock(iterator, block);
            break;
        case TAIL_CANDIDATE:
            pzxBlock = new PZXPulseBlock(blockPulseList);
            break;
    }
    return pzxBlock;
}
 
开发者ID:fmeunier,项目名称:wav2pzx,代码行数:26,代码来源:PZXBuilder.java

示例9: getPzxDataBlock

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
private static PZXDataBlock getPzxDataBlock(PeekingIterator<TapeBlock> iterator, TapeBlock block) {
    long tailLength = getTailLength(iterator);

    List<Long> zeroPulseLengths = block.getZeroBit().getPulses();
    List<Long> onePulseLengths = block.getOneBit().getPulses();
    DataBuilder dataBuilder = new DataBuilder();

    ImmutableList<Long> pulseLengths = block.getPulseList().getPulseLengths();
    for (int i = 0; i < pulseLengths.size(); i += 2) {
        ImmutableList<Long> pulses = pulseLengths.subList(i, i + 2);
        if (isSpecifiedPulseSequence(zeroPulseLengths, pulses)) {
            dataBuilder.addBit(0);
        } else if (isSpecifiedPulseSequence(onePulseLengths, pulses)) {
            dataBuilder.addBit(1);
        }
        // FIXME: Some kind of error, fall back to PulseBlock?
    }

    int numBitsInLastByte = dataBuilder.getNumBitsInCurrentByte();
    return new PZXDataBlock(block.getPulseList(), zeroPulseLengths, onePulseLengths, tailLength,
            numBitsInLastByte, dataBuilder.getData());
}
 
开发者ID:fmeunier,项目名称:wav2pzx,代码行数:23,代码来源:PZXBuilder.java

示例10: testExpirationTime

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
@Test
public void testExpirationTime() {
    long start = System.currentTimeMillis();
    Iterator<Long> unlimitedIter = countForever();
    PeekingIterator<Long> limitedIter = TimeLimitedIterator.create(unlimitedIter, Duration.millis(10), 0);
    long previous = -1;
    while (limitedIter.hasNext()) {
        long next = limitedIter.next();
        assertEquals(next, previous + 1);
        previous = next;
    }
    long stop = System.currentTimeMillis();
    long elapsed = stop - start;

    assertTrue(elapsed >= 10);
    assertTrue(elapsed < 100);  // be fairly relaxed about the upper bound to avoid spurious test failures on slow machines.
    assertEquals(unlimitedIter.next(), (previous + 1));
}
 
开发者ID:bazaarvoice,项目名称:emodb,代码行数:19,代码来源:TimeLimitedIteratorTest.java

示例11: readAll

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
void readAll(String channel, SlabFilter filter, EventSink sink, ConsistencyLevel consistency) {
    // PeekingIterator is needed so that we can look ahead and see the next slab Id
    PeekingIterator<Column<ByteBuffer>> manifestColumns = Iterators.peekingIterator(executePaginated(
            _keyspace.prepareQuery(ColumnFamilies.MANIFEST, consistency)
                    .getKey(channel)
                    .withColumnRange(new RangeBuilder().setLimit(50).build())
                    .autoPaginate(true)).iterator());

    while (manifestColumns.hasNext()) {
        Column<ByteBuffer> manifestColumn = manifestColumns.next();
        ByteBuffer slabId = manifestColumn.getName();
        ByteBuffer nextSlabId = manifestColumns.hasNext() ? manifestColumns.peek().getName() : null;
        boolean open = manifestColumn.getBooleanValue();
        if (filter != null && !filter.accept(slabId, open, nextSlabId)) {
            continue;
        }
        if (!readSlab(channel, slabId, new SlabCursor(), open, sink)) {
            break;
        }
    }
}
 
开发者ID:bazaarvoice,项目名称:emodb,代码行数:22,代码来源:AstyanaxEventReaderDAO.java

示例12: createReversedLeafIterator

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
private PeekingIterator<ILeafNode> createReversedLeafIterator(INode root, INode candidate, LinkedList<ILeafNode> sameGrammarElement) {
	EObject grammarElement = null;
	PeekingIterator<ILeafNode> iterator = Iterators.peekingIterator(Iterators.filter(root.getAsTreeIterable().reverse().iterator(), ILeafNode.class));
	// traverse until we find the current candidate
	while(iterator.hasNext()) {
		ILeafNode next = iterator.next();
		if (candidate.equals(next)) {
			break;
		} else if (next.getTotalLength() == 0) {
			EObject otherGrammarElement = tryGetGrammarElementAsRule(next);
			if (grammarElement == null) {
				grammarElement = otherGrammarElement;
			}
			if (otherGrammarElement.equals(grammarElement)) {
				sameGrammarElement.add(next);
			} else {
				sameGrammarElement.removeLast();
			}
		}
	}
	return iterator;
}
 
开发者ID:eclipse,项目名称:xtext-core,代码行数:23,代码来源:IndentationAwareCompletionPrefixProvider.java

示例13: restoreOneTransaction

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
/**
 * Restore the contents of one transaction to Datastore.
 *
 * <p>The objects to delete are listed in the {@link CommitLogManifest}, which will be the first
 * object in the iterable. The objects to save follow, each as a {@link CommitLogMutation}. We
 * restore by deleting the deletes and recreating the saves from their proto form. We also save
 * the commit logs themselves back to Datastore, so that the commit log system itself is
 * transparently restored alongside the data.
 *
 * @return the manifest, for use in restoring the {@link CommitLogBucket}.
 */
private CommitLogManifest restoreOneTransaction(PeekingIterator<ImmutableObject> commitLogs) {
  final CommitLogManifest manifest = (CommitLogManifest) commitLogs.next();
  Result<?> deleteResult = deleteAsync(manifest.getDeletions());
  List<Entity> entitiesToSave = Lists.newArrayList(ofy().save().toEntity(manifest));
  while (commitLogs.hasNext() && commitLogs.peek() instanceof CommitLogMutation) {
    CommitLogMutation mutation = (CommitLogMutation) commitLogs.next();
    entitiesToSave.add(ofy().save().toEntity(mutation));
    entitiesToSave.add(EntityTranslator.createFromPbBytes(mutation.getEntityProtoBytes()));
  }
  saveRaw(entitiesToSave);
  try {
    deleteResult.now();
  } catch (Exception e) {
    retrier.callWithRetry(
        () -> deleteAsync(manifest.getDeletions()).now(), RuntimeException.class);
  }
  return manifest;
}
 
开发者ID:google,项目名称:nomulus,代码行数:30,代码来源:RestoreCommitLogsAction.java

示例14: match

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
/**
 * Attempt to match the desired properties to a sequence of known properties.
 * <p>
 * Returns a list of the same length as the original. Entries are:
 * - Optional.empty(): the property was satisfied completely
 * - non-empty: the (simplified) property that was not satisfied
 */
public static <T> List<Optional<LocalProperty<T>>> match(List<LocalProperty<T>> actuals, List<LocalProperty<T>> desired)
{
    // After normalizing actuals, each symbol should only appear once
    PeekingIterator<LocalProperty<T>> actualIterator = peekingIterator(normalizeAndPrune(actuals).iterator());

    Set<T> constants = new HashSet<>();
    boolean consumeMoreActuals = true;
    List<Optional<LocalProperty<T>>> result = new ArrayList<>(desired.size());
    for (LocalProperty<T> desiredProperty : desired) {
        while (consumeMoreActuals && actualIterator.hasNext() && desiredProperty.isSimplifiedBy(actualIterator.peek())) {
            constants.addAll(actualIterator.next().getColumns());
        }
        Optional<LocalProperty<T>> simplifiedDesired = desiredProperty.withConstants(constants);
        consumeMoreActuals &= !simplifiedDesired.isPresent(); // Only continue processing actuals if all previous desired properties were fully satisfied
        result.add(simplifiedDesired);
    }
    return result;
}
 
开发者ID:y-lan,项目名称:presto,代码行数:26,代码来源:LocalProperties.java

示例15: visitStatements

import com.google.common.collect.PeekingIterator; //导入依赖的package包/类
private void visitStatements(List<? extends StatementTree> statements) {
  boolean first = true;
  PeekingIterator<StatementTree> it = Iterators.peekingIterator(statements.iterator());
  dropEmptyDeclarations();
  while (it.hasNext()) {
    StatementTree tree = it.next();
    builder.forcedBreak();
    if (!first) {
      builder.blankLineWanted(BlankLineWanted.PRESERVE);
    }
    markForPartialFormat();
    first = false;
    List<VariableTree> fragments = variableFragments(it, tree);
    if (!fragments.isEmpty()) {
      visitVariables(
          fragments,
          DeclarationKind.NONE,
          canLocalHaveHorizontalAnnotations(fragments.get(0).getModifiers()));
    } else {
      scan(tree, null);
    }
  }
}
 
开发者ID:google,项目名称:google-java-format,代码行数:24,代码来源:JavaInputAstVisitor.java


注:本文中的com.google.common.collect.PeekingIterator类示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。