java.util.Queue#iterator ( )源码实例Demo

下面列出了java.util.Queue#iterator ( ) 实例代码,或者点击链接到github查看源代码,也可以在右侧发表评论。

源代码1 项目: streamsupport   文件: MOAT.java
private static void testQueueIteratorRemove(Queue<Integer> q) {
    System.err.printf("testQueueIteratorRemove %s%n",
                      q.getClass().getSimpleName());
    q.clear();
    for (int i = 0; i < 5; i++)
        q.add(i);
    Iterator<Integer> it = q.iterator();
    check(it.hasNext());
    for (int i = 3; i >= 0; i--)
        q.remove(i);
    equal(it.next(), 0);
    equal(it.next(), 4);

    q.clear();
    for (int i = 0; i < 5; i++)
        q.add(i);
    it = q.iterator();
    equal(it.next(), 0);
    check(it.hasNext());
    for (int i = 1; i < 4; i++)
        q.remove(i);
    equal(it.next(), 1);
    equal(it.next(), 4);
}
 
源代码2 项目: java-dcp-client   文件: StreamEventBuffer.java
/**
 * Discard any buffered events in the given vBucket with sequence numbers
 * higher than the given sequence number.
 */
private void rollback(final short vbucket, final long toSeqno) {
  final Queue<BufferedEvent> queue = partitionQueues.get(vbucket);

  synchronized (queue) {
    for (Iterator<BufferedEvent> i = queue.iterator(); i.hasNext(); ) {
      final BufferedEvent event = i.next();
      final boolean eventSeqnoIsGreaterThanRollbackSeqno = Long.compareUnsigned(event.seqno, toSeqno) > 0;
      if (eventSeqnoIsGreaterThanRollbackSeqno) {
        LOGGER.trace("Dropping event with seqno {} from stream buffer for partition {}", event.seqno, vbucket);
        event.discard();
        i.remove();
      }
    }
  }
}
 
@Test
public void iteratorModificationAdd() throws Exception {
    Queue<Integer> queue = new ConcurrentEvictingQueue<>(2);
    queue.addAll(asList(4, 5));
    Iterator<Integer> iterator = queue.iterator();

    queue.peek();

    assertThat(iterator.hasNext()).isTrue();
    Integer first = iterator.next();
    assertThat(first).isEqualTo(4);

    queue.add(6);
    assertThat(iterator.hasNext()).isTrue();

    exception.expect(ConcurrentModificationException.class);
    iterator.next();
}
 
源代码4 项目: servicetalk   文件: TestExecutor.java
@Nullable
private static boolean executeOne(Queue<RunnableWrapper> tasks, AtomicInteger taskCount) {
    Iterator<RunnableWrapper> i = tasks.iterator();
    if (i.hasNext()) {
        final Runnable task = i.next();
        i.remove();
        taskCount.incrementAndGet();
        task.run();
        return true;
    }
    return false;
}
 
源代码5 项目: Velocity   文件: AvailableCommands.java
@Override
public void decode(ByteBuf buf, Direction direction, ProtocolVersion protocolVersion) {
  int commands = ProtocolUtils.readVarInt(buf);
  WireNode[] wireNodes = new WireNode[commands];
  for (int i = 0; i < commands; i++) {
    wireNodes[i] = deserializeNode(buf, i);
  }

  // Iterate over the deserialized nodes and attempt to form a graph. We also resolve any cycles
  // that exist.
  Queue<WireNode> nodeQueue = new ArrayDeque<>(Arrays.asList(wireNodes));
  while (!nodeQueue.isEmpty()) {
    boolean cycling = false;

    for (Iterator<WireNode> it = nodeQueue.iterator(); it.hasNext(); ) {
      WireNode node = it.next();
      if (node.toNode(wireNodes)) {
        cycling = true;
        it.remove();
      }
    }

    if (!cycling) {
      // Uh-oh. We can't cycle. This is bad.
      throw new IllegalStateException("Stopped cycling; the root node can't be built.");
    }
  }

  int rootIdx = ProtocolUtils.readVarInt(buf);
  rootNode = (RootCommandNode<Object>) wireNodes[rootIdx].built;
}
 
源代码6 项目: redisson   文件: RedissonPriorityQueueTest.java
private void checkIterator(Queue<Integer> set, Queue<Integer> setCopy) {
    for (Iterator<Integer> iterator = set.iterator(); iterator.hasNext();) {
        Integer value = iterator.next();
        if (!setCopy.remove(value)) {
            Assert.fail();
        }
    }

    Assert.assertEquals(0, setCopy.size());
}
 
源代码7 项目: actor4j-core   文件: PodReplicationController.java
public void undeployPods(String domain) {
	systemLogger().info(String.format("[REPLICATION] Domain '%s' undeploying", domain));
	
	Queue<UUID> queue = system.getPodDomains().get(domain);
	Iterator<UUID> iterator = queue.iterator();
	while (iterator.hasNext()) {
		UUID id = iterator.next();
		systemLogger().info(String.format("[REPLICATION] PodActor (%s, %s) stopping", domain, id));
		system.send(new ActorMessage<>(null, STOP, system.SYSTEM_ID, id));
		iterator.remove();
	}
	system.getPodDomains().remove(domain);
}
 
源代码8 项目: JAADAS   文件: SmallPriorityQueueTest.java
@Test
public void testIteratorRemove() {
	Queue<Integer> q = PriorityQueue.of(universe1);
	
	Iterator<Integer> it = q.iterator();
	
	while (it.hasNext()) {
		Integer i = it.next();
		assertTrue(q.contains(i));
		it.remove();
		assertFalse(q.contains(i));
	}
}
 
源代码9 项目: JAADAS   文件: SmallPriorityQueueTest.java
@Test(expected=NoSuchElementException.class)
public void testIteratorOutOfBounds() {
	Queue<Integer> q = PriorityQueue.of(universe1);
	
	Iterator<Integer> it = q.iterator();
	
	while (it.hasNext()) {
		it.next();
	}
	it.next();
}
 
源代码10 项目: JAADAS   文件: SmallPriorityQueueTest.java
@Test(expected=IllegalStateException.class)
public void testIteratorDoubleRemove() {
	Queue<Integer> q = PriorityQueue.of(universe1);
	
	Iterator<Integer> it = q.iterator();
	
	while (it.hasNext()) {
		it.next();
		it.remove();
		it.remove();
	}
}
 
源代码11 项目: jason   文件: SelectEvent.java
public Event selectEvent(Queue<Event> events) {
    Iterator<Event> ie = events.iterator();
    while (ie.hasNext()) {
        un.clear();
        Event e = ie.next();
        if (un.unifies(gold, e.getTrigger()) || un.unifies(restart, e.getTrigger())) {
            //getTS().getLogger().info("custom select event "+e);
            ie.remove();
            return e;
        }
    }
    return super.selectEvent(events);
}
 
源代码12 项目: caffeine   文件: SingleConsumerQueueTest.java
@Test(dataProvider = "populated", expectedExceptions = IllegalStateException.class)
public void iterator_removal_duplicate(Queue<Integer> queue) {
  Iterator<Integer> it = queue.iterator();
  it.next();
  it.remove();
  it.remove();
}
 
void purgeCancelledScheduledTasks() {
    Queue<ScheduledFutureTask<?>> scheduledTaskQueue = this.scheduledTaskQueue;
    if (isNullOrEmpty(scheduledTaskQueue)) {
        return;
    }
    Iterator<ScheduledFutureTask<?>> i = scheduledTaskQueue.iterator();
    while (i.hasNext()) {
        ScheduledFutureTask<?> task = i.next();
        if (task.isCancelled()) {
            i.remove();
        }
    }
}
 
源代码14 项目: caffeine   文件: SingleConsumerQueueTest.java
@Test(dataProvider = "populated")
public void iterator_removal_toEmpty(Queue<Integer> queue) {
  for (Iterator<Integer> it = queue.iterator(); it.hasNext();) {
    it.next();
    it.remove();
  }
  assertThat(queue, is(deeplyEmpty()));
}
 
源代码15 项目: caffeine   文件: SingleConsumerQueueTest.java
@Test(dataProvider = "populated")
public void iterator_removal(Queue<Integer> queue) {
  Iterator<Integer> it = queue.iterator();
  it.next();
  it.remove();
}
 
源代码16 项目: AcDisplay   文件: TaskQueueThread.java
@Override
public void run() {
    Timber.tag(TAG).d("Starting thread...");
    super.run();

    Queue<T> queue = new ConcurrentLinkedQueue<>();
    while (mRunning) {
        synchronized (this) {
            if (mQueue.isEmpty())
                try {
                    // Wait for a next #sendEvent(Event),
                    // where this thread will be unlocked.
                    mWaiting = true;
                    wait();
                } catch (InterruptedException ignored) {
                } finally {
                    mWaiting = false;
                }

            // Move all pending events to a local copy, so we don't need
            // to block main queue.
            while (!mQueue.isEmpty()) {
                queue.add(mQueue.poll());
            }
        }

        if (isLost()) {
            mRunning = false;
            break;
        }

        Iterator<T> iterator = queue.iterator();
        while (iterator.hasNext()) {
            T object = iterator.next();
            // ~~
            onHandleTask(object);
            // ~~
            iterator.remove();
        }
    }


    Timber.tag(TAG).d("Stopping thread...");
}
 
源代码17 项目: openjdk-jdk9   文件: PriorityQueueSort.java
public static void main(String[] args) {
    int n = 10000;
    if (args.length > 0)
        n = Integer.parseInt(args[0]);

    List<Integer> sorted = new ArrayList<>(n);
    for (int i = 0; i < n; i++)
        sorted.add(new Integer(i));
    List<Integer> shuffled = new ArrayList<>(sorted);
    Collections.shuffle(shuffled);

    Queue<Integer> pq = new PriorityQueue<>(n, new MyComparator());
    for (Iterator<Integer> i = shuffled.iterator(); i.hasNext(); )
        pq.add(i.next());

    List<Integer> recons = new ArrayList<>();
    while (!pq.isEmpty())
        recons.add(pq.remove());
    if (!recons.equals(sorted))
        throw new RuntimeException("Sort test failed");

    recons.clear();
    pq = new PriorityQueue<>(shuffled);
    while (!pq.isEmpty())
        recons.add(pq.remove());
    if (!recons.equals(sorted))
        throw new RuntimeException("Sort test failed");

    // Remove all odd elements from queue
    pq = new PriorityQueue<>(shuffled);
    for (Iterator<Integer> i = pq.iterator(); i.hasNext(); )
        if ((i.next().intValue() & 1) == 1)
            i.remove();
    recons.clear();
    while (!pq.isEmpty())
        recons.add(pq.remove());

    for (Iterator<Integer> i = sorted.iterator(); i.hasNext(); )
        if ((i.next().intValue() & 1) == 1)
            i.remove();

    if (!recons.equals(sorted))
        throw new RuntimeException("Iterator remove test failed.");
}
 
源代码18 项目: pentaho-kettle   文件: MetricsUtil.java
/**
 * Calculates the durations between the START and STOP snapshots per metric description and subject (if any)
 *
 * @param logChannelId
 *          the id of the log channel to investigate
 * @return the duration in ms
 */
public static List<MetricsDuration> getDurations( String logChannelId ) {
  Map<String, MetricsSnapshotInterface> last = new HashMap<String, MetricsSnapshotInterface>();
  Map<String, MetricsDuration> map = new HashMap<String, MetricsDuration>();

  Queue<MetricsSnapshotInterface> metrics = MetricsRegistry.getInstance().getSnapshotList( logChannelId );

  Iterator<MetricsSnapshotInterface> iterator = metrics.iterator();
  while ( iterator.hasNext() ) {
    MetricsSnapshotInterface snapshot = iterator.next();

    // Do we have a start point in the map?
    //
    String key =
      snapshot.getMetric().getDescription()
        + ( snapshot.getSubject() == null ? "" : ( " - " + snapshot.getSubject() ) );
    MetricsSnapshotInterface lastSnapshot = last.get( key );
    if ( lastSnapshot == null ) {
      lastSnapshot = snapshot;
      last.put( key, lastSnapshot );
    } else {
      // If we have a START-STOP range, calculate the duration and add it to the duration map...
      //
      MetricsInterface metric = lastSnapshot.getMetric();
      if ( metric.getType() == MetricsSnapshotType.START
        && snapshot.getMetric().getType() == MetricsSnapshotType.STOP ) {
        long extraDuration = snapshot.getDate().getTime() - lastSnapshot.getDate().getTime();

        MetricsDuration metricsDuration = map.get( key );
        if ( metricsDuration == null ) {
          metricsDuration =
            new MetricsDuration(
              lastSnapshot.getDate(), metric.getDescription(), lastSnapshot.getSubject(), logChannelId,
              extraDuration );
        } else {
          metricsDuration.setDuration( metricsDuration.getDuration() + extraDuration );
          metricsDuration.incrementCount();
          if ( metricsDuration.getEndDate().getTime() < snapshot.getDate().getTime() ) {
            metricsDuration.setEndDate( snapshot.getDate() );
          }
        }
        map.put( key, metricsDuration );
      }
    }
  }

  return new ArrayList<MetricsDuration>( map.values() );
}
 
源代码19 项目: algorithms   文件: RedBlackTree.java
public Iterator<K> iterator() {
    Queue<K> keys = new ArrayDeque<K>();
    inorder(keys, root);
    return keys.iterator();
}
 
源代码20 项目: algorithms   文件: BST.java
public Iterator<K> iterator() {
    Queue<K> keys = new ArrayDeque<K>();
    inorder(keys, root);
    return keys.iterator();
}