java.util.ArrayDeque#pollFirst ( )源码实例Demo

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

源代码1 项目: doov   文件: AstJavascriptVisitor.java
/**
 * age_at operator specials cases for the parameter in moment.js
 *
 * @param stack the deque of the parameters not translated yet to Javascript predicate
 */
private void formatAgeAtOperator(ArrayDeque<Element> stack) {
    ArrayDeque<Element> stackTmp = new ArrayDeque<>();
    if (stack.getFirst().getReadable() == with || stack.getFirst().getReadable() == plus
            || stack.getFirst().getReadable() == minus) {
        if (stack.getFirst().getReadable() == with) {
            stack.pollFirst();
            stackTmp.add(stack.pollFirst());
            manageStack(stackTmp);
        } else { // working on plus and minus operators
            Element ope = stack.pollFirst(); // need the three first elements of the stack to manage
            Element duration = stack.pollFirst(); // these operators
            Element unit = stack.pollFirst();
            stackTmp.add(ope);
            stackTmp.add(duration);
            stackTmp.add(unit);
            manageStack(stackTmp);
        }
    }
}
 
源代码2 项目: cs-summary-reflection   文件: MaxInWindowSize.java
/**
 * 滑动窗口应当是队列,但为了得到滑动窗口的最大值,队列序可以从两端删除元素,因此使用双端队列。 对新来的元素k,将其与双端队列中的元素相比较
 * 1)前面比k小的,直接移出队列(因为不再可能成为后面滑动窗口的最大值了!), 2)前面比k大的X,比较两者下标,判断X是否已不在窗口之内,不在了,直接移出队列
 * 队列的第一个元素是滑动窗口中的最大值
 */
public ArrayList<Integer> maxInWindows(int[] num, int size) {
    ArrayList<Integer> list = new ArrayList<>();
    if (size == 0) return list;
    int start = 0;
    // 用来保存可能是滑动窗口最大值的数字的下标
    ArrayDeque<Integer> index = new ArrayDeque<>();
    for (int i = 0; i < num.length; i++) {
        start = i - size + 1;
        if (index.isEmpty()) index.add(i);
        // 如果队列的头部元素已经从滑动窗口里滑出,滑出的数字需要从队列的头部删除
        else if (start > index.peekFirst()) index.pollFirst();
        // 数组:{2,3,4,2,6,2,5,1}
        // 如果已有数字小于待存入的数据, 这些数字已经不可能是滑动窗口的最大值
        // 因此它们将会依次地从队尾删除
        while ((!index.isEmpty()) && num[index.peekLast()] <= num[i]) index.pollLast();
        index.add(i);
        if (start >= 0) list.add(num[index.peekFirst()]);
    }
    return list;
}
 
源代码3 项目: jlibs   文件: XPathParser.java
@Override
public void endFunction() throws SAXPathException{
    ArrayDeque params = popFrame();
    javax.xml.namespace.QName name = (javax.xml.namespace.QName)params.pollFirst();
    if(name.getNamespaceURI().length()==0)
        push(createFunction(name.getLocalPart(), params).simplify());
    else{
        int noOfParams = params.size();
        XPathFunction function = functionResolver.resolveFunction(name, noOfParams);
        if(function==null)
            throw new SAXPathException("Unknown Function: "+name);
        FunctionCall functionCall = new FunctionCall(new Functions.UserFunction(name.getNamespaceURI(), name.getLocalPart(), function), noOfParams);
        for(int i=0; i<noOfParams; i++)
            functionCall.addMember(params.pollFirst(), i);
        push(functionCall);
    }
}
 
源代码4 项目: flink   文件: BufferStorageTestBase.java
private static void assertNextBufferOrEvent(
		ArrayDeque<ArrayDeque<BufferOrEvent>> expectedRolledSequence,
		BufferStorage bufferStorage) throws IOException {
	while (!expectedRolledSequence.isEmpty() && expectedRolledSequence.peekFirst().isEmpty()) {
		expectedRolledSequence.pollFirst();
	}

	Optional<BufferOrEvent> next = bufferStorage.pollNext();
	if (expectedRolledSequence.isEmpty()) {
		assertFalse(next.isPresent());
		return;
	}

	while (!next.isPresent() && !bufferStorage.isEmpty()) {
		next = bufferStorage.pollNext();
	}

	assertTrue(next.isPresent());
	BufferOrEvent actualBufferOrEvent = next.get();
	BufferOrEvent expectedBufferOrEvent = expectedRolledSequence.peekFirst().pollFirst();

	if (expectedBufferOrEvent.isEvent()) {
		assertEquals(expectedBufferOrEvent.getChannelIndex(), actualBufferOrEvent.getChannelIndex());
		assertEquals(expectedBufferOrEvent.getEvent(), actualBufferOrEvent.getEvent());
	} else {
		validateBuffer(
			actualBufferOrEvent,
			expectedBufferOrEvent.getSize(),
			expectedBufferOrEvent.getChannelIndex());
	}
}
 
源代码5 项目: EmergingTechnology   文件: WorldTickHandler.java
@SubscribeEvent
public void tickEnd(TickEvent.WorldTickEvent event) {
    if (event.side != Side.SERVER) {
        return;
    }

    if (event.phase == TickEvent.Phase.END) {

        World world = event.world;
        int dim = world.provider.getDimension();

        ArrayDeque<ChunkPos> chunks = chunksToGen.get(dim);

        if (chunks != null && !chunks.isEmpty()) {
            ChunkPos c = chunks.pollFirst();
            long worldSeed = world.getSeed();
            Random rand = new Random(worldSeed);
            long xSeed = rand.nextLong() >> 2 + 1L;
            long zSeed = rand.nextLong() >> 2 + 1L;
            rand.setSeed(xSeed * c.x + zSeed * c.z ^ worldSeed);
            OreGenerator.instance.generateWorld(rand, c.x, c.z, world, false);
            chunksToGen.put(dim, chunks);
        } else if (chunks != null) {
            chunksToGen.remove(dim);
        }
    }
}
 
源代码6 项目: YouTubeModdingTutorial   文件: WorldTickHandler.java
@SubscribeEvent
public void tickEnd(TickEvent.WorldTickEvent event) {
    if (event.side != Side.SERVER) {
        return;
    }

    if (event.phase == TickEvent.Phase.END) {

        World world = event.world;
        int dim = world.provider.getDimension();

        ArrayDeque<ChunkPos> chunks = chunksToGen.get(dim);

        if (chunks != null && !chunks.isEmpty()) {
            ChunkPos c = chunks.pollFirst();
            long worldSeed = world.getSeed();
            Random rand = new Random(worldSeed);
            long xSeed = rand.nextLong() >> 2 + 1L;
            long zSeed = rand.nextLong() >> 2 + 1L;
            rand.setSeed(xSeed * c.x + zSeed * c.z ^ worldSeed);
            OreGenerator.instance.generateWorld(rand, c.x, c.z, world, false);
            chunksToGen.put(dim, chunks);
        } else if (chunks != null) {
            chunksToGen.remove(dim);
        }
    }
}
 
public int[] maxSlidingWindow(int[] nums, int k) {
    int len = nums.length;
    // 特判
    if (len == 0) {
        return new int[]{};
    }
    // 结果集
    List<Integer> res = new ArrayList<>();
    // 滑动窗口,注意:保存的是索引值
    ArrayDeque<Integer> deque = new ArrayDeque<>(k);

    for (int i = 0; i < len; i++) {
        // 当元素从左边界滑出的时候,如果它恰恰好是滑动窗口的最大值
        // 那么将它弹出
        if (i >= k && i - k == deque.getFirst()) {
            deque.pollFirst();
        }

        // 如果滑动窗口非空,新进来的数比队列里已经存在的数还要大
        // 则说明已经存在数一定不会是滑动窗口的最大值(它们毫无出头之日)
        // 将它们弹出
        while (!deque.isEmpty() && nums[deque.peekLast()] <= nums[i]) {
            deque.pollLast();
        }
        deque.add(i);
        // 队首一定是滑动窗口的最大值的索引
        if (i >= k - 1) {
            res.add(nums[deque.peekFirst()]);
        }
    }

    int size = res.size();
    int[] result = new int[size];

    for (int i = 0; i < size; i++) {
        result[i] = res.get(i);
    }
    return result;
}
 
源代码8 项目: aeron   文件: ArchiveConductor.java
private int runTasks(final ArrayDeque<Runnable> taskQueue)
{
    int workCount = 0;

    Runnable runnable;
    while (null != (runnable = taskQueue.pollFirst()))
    {
        runnable.run();
        workCount += 1;
    }

    return workCount;
}
 
源代码9 项目: aeron   文件: ServiceAck.java
static void removeHead(final ArrayDeque<ServiceAck>[] queues)
{
    for (final ArrayDeque<ServiceAck> queue : queues)
    {
        queue.pollFirst();
    }
}
 
源代码10 项目: swift-t   文件: TaskQueue.java
/**
 * TODO: each thread should hold local reference to own deque
 * @return a task, or null if nothing available
 */
public Task getTask(int threadNum) {
  // Targeted have highest priority
  Task res = targeted.get(threadNum).pollLast();
  if (res != null)
    return res;
  
  // Next, try to see if something in local deque
  ArrayDeque<Task> myDeque = regular.get(threadNum);
  synchronized (myDeque) {
    res = myDeque.pollLast();
  }
  if (res != null)
    return res;
  
  // Finally, search other deques to steal work
  // TODO: exit condition - detect idle, or go to sleep
  Random r = new Random();
  while (true) {
    int deque = r.nextInt(numThreads - 1);
    if (deque >= threadNum)
      deque++;
    
    ArrayDeque<Task> otherDeque = regular.get(threadNum);
    // Task from other end
    synchronized (otherDeque) {
      res = otherDeque.pollFirst();
    }
    if (res != null)
      return res;      
  }
}
 
源代码11 项目: android-vlc-remote   文件: File.java
/**
 * Get the normalized path for the given file path.
 * Any parent directories (..) will be resolved.
 * @param file file path
 * @return 
 */
public static String getNormalizedPath(String file) {
    Matcher m = schemedPathPattern.matcher(file);
    if(!m.find()) {
        return Directory.ROOT_DIRECTORY;
    }
    String scheme = m.group(1);
    String path = m.group(2);
    if(scheme == null) {
        scheme = "";
    }
    String[] st = path.split("(\\\\|/)+");
    ArrayDeque<String> segmentList = new ArrayDeque<String>();
    for(String segment : st) {
        if("..".equals(segment)) {
            segmentList.pollFirst();
            continue;
        }
        segmentList.offerFirst(segment);
    }
    if(segmentList.isEmpty() && scheme.isEmpty()) {
        return Directory.ROOT_DIRECTORY;
    }
    StringBuilder sb = new StringBuilder();
    sb.append(scheme);
    while(!segmentList.isEmpty()) {
        sb.append(segmentList.pollLast());
        if(segmentList.peekLast() != null) {
            sb.append('/');
        }
    }
    return sb.length() == 0 ? Directory.ROOT_DIRECTORY : sb.toString();
}
 
源代码12 项目: doov   文件: AstJavascriptVisitor.java
/**
 * This function manage the different parameters of the predicate
 *
 * @param stack A deque of the predicate parameters
 */
private void manageStack(ArrayDeque<Element> stack) {
    while (stack.size() > 0) {
        Element e = stack.pollFirst();
        switch (e.getType()) {
            case FIELD:
                write(e.toString());
                break;
            case OPERATOR:
                manageOperator((DefaultOperator) e.getReadable(), stack);
                break;
            case VALUE:
                if (StringUtils.isNumeric(e.toString())) {
                    write(e.toString());
                } else {
                    write("\'" + e.toString() + "\'");
                }
                break;
            case STRING_VALUE:
                if (use_regexp == 1) {
                    String tmp = e.toString();
                    if (is_match == 1) {
                        is_match = 0;
                    } else {
                        tmp = formatRegexp(tmp);
                    }
                    write(tmp);
                    if (start_with_count > 0) {
                        write(".*");
                        start_with_count--;
                    } else if (end_with_count > 0) {
                        write("$");
                        end_with_count--;
                    }
                    write("/");
                    use_regexp = 0;
                } else {
                    write("\'" + e.toString() + "\'");
                }
                break;
            case PARENTHESIS_LEFT:
            case PARENTHESIS_RIGHT:
            case UNKNOWN:
            default:
                break;
        }
    }
}
 
源代码13 项目: litho   文件: DataFlowGraph.java
@GuardedBy("this")
private void regenerateSortedNodes() {
  mSortedNodes.clear();

  if (mBindings.size() == 0) {
    return;
  }

  final ArraySet<ValueNode> leafNodes = new ArraySet<>();
  final SimpleArrayMap<ValueNode, Integer> nodesToOutputsLeft = new SimpleArrayMap<>();

  for (int i = 0, bindingsSize = mBindings.size(); i < bindingsSize; i++) {
    final ArrayList<ValueNode> nodes = mBindings.get(i).getAllNodes();
    for (int j = 0, nodesSize = nodes.size(); j < nodesSize; j++) {
      final ValueNode node = nodes.get(j);
      final int outputCount = node.getOutputCount();
      if (outputCount == 0) {
        leafNodes.add(node);
      } else {
        nodesToOutputsLeft.put(node, outputCount);
      }
    }
  }

  if (!nodesToOutputsLeft.isEmpty() && leafNodes.isEmpty()) {
    throw new DetectedCycleException(
        "Graph has nodes, but they represent a cycle with no leaf nodes!");
  }

  final ArrayDeque<ValueNode> nodesToProcess = new ArrayDeque<>();
  nodesToProcess.addAll(leafNodes);

  while (!nodesToProcess.isEmpty()) {
    final ValueNode next = nodesToProcess.pollFirst();
    mSortedNodes.add(next);
    NodeState nodeState = mNodeStates.get(next);
    if (nodeState == null) {
      String message =
          next.getClass().getSimpleName() + " : InputNames " + next.buildDebugInputsString();
      // Added for debugging T67342661
      ComponentsReporter.emitMessage(
          ComponentsReporter.LogLevel.ERROR, STATE_NOT_INTIALIZED_FOR_VALUE_NODE, message);
    }
    for (ValueNode input : next.getAllInputs()) {
      final int outputsLeft = nodesToOutputsLeft.get(input) - 1;
      nodesToOutputsLeft.put(input, outputsLeft);
      if (outputsLeft == 0) {
        nodesToProcess.addLast(input);
      } else if (outputsLeft < 0) {
        throw new DetectedCycleException("Detected cycle.");
      }
    }
  }

  int expectedTotalNodes = nodesToOutputsLeft.size() + leafNodes.size();
  if (mSortedNodes.size() != expectedTotalNodes) {
    throw new DetectedCycleException(
        "Had unreachable nodes in graph -- this likely means there was a cycle");
  }

  Collections.reverse(mSortedNodes);
  mIsDirty = false;
}
 
源代码14 项目: streamex   文件: OrderedCancellableSpliterator.java
@Override
public boolean tryAdvance(Consumer<? super A> action) {
    Spliterator<T> source = this.source;
    if (source == null || localCancelled) {
        this.source = null;
        return false;
    }
    A acc = supplier.get();
    try {
        source.forEachRemaining(t -> {
            accumulator.accept(acc, t);
            if (cancelPredicate.test(acc)) {
                cancelSuffix();
                throw new CancelException();
            }
            if (localCancelled) {
                throw new CancelException();
            }
        });
    } catch (CancelException ex) {
        if (localCancelled) {
            return false;
        }
    }
    this.source = null;
    A result = acc;
    while (true) {
        if (prefix == null && suffix == null) {
            action.accept(result);
            return true;
        }
        ArrayDeque<A> res = new ArrayDeque<>();
        res.offer(result);
        synchronized (lock) {
            if (localCancelled)
                return false;
            OrderedCancellableSpliterator<T, A> s = prefix;
            while (s != null) {
                if (s.payload == null)
                    break;
                res.offerFirst(s.payload);
                s = s.prefix;
            }
            prefix = s;
            if (s != null) {
                s.suffix = this;
            }
            s = suffix;
            while (s != null) {
                if (s.payload == null)
                    break;
                res.offerLast(s.payload);
                s = s.suffix;
            }
            suffix = s;
            if (s != null) {
                s.prefix = this;
            }
            if (res.size() == 1) {
                if (prefix == null && suffix == null) {
                    action.accept(result);
                    return true;
                }
                this.payload = result;
                break;
            }
        }
        result = res.pollFirst();
        while (!res.isEmpty()) {
            result = combiner.apply(result, res.pollFirst());
            if (cancelPredicate.test(result)) {
                cancelSuffix();
            }
        }
    }
    return false;
}
 
源代码15 项目: pnc   文件: DefaultFileTranser.java
@Override
public StringBuffer downloadFileToStringBuilder(StringBuffer logsAggregate, URI uri) throws TransferException {
    try {
        logger.debug("Downloading file to String Buffer from {}", uri);

        ArrayDeque<String> logLines = new ArrayDeque<>();

        HttpURLConnection connection = (HttpURLConnection) uri.toURL().openConnection();
        connection.setRequestMethod("GET");

        connection.setDoOutput(true);
        connection.setDoInput(true);

        connection.setConnectTimeout(connectTimeout);
        connection.setReadTimeout(readTimeout);

        Consumer<String> removedLines = (removedLine) -> {
            fullyDownloaded = false;
            logger.debug("Dropped log line from URI {}: {}.", uri, removedLine);
        };

        try (InputStream inputStream = connection.getInputStream()) {
            Charset charset = Charset.forName(ENCODING);
            StringUtils.readStream(inputStream, charset, logLines, maxDownloadSize, removedLines);
        }

        logsAggregate.append("==== ").append(uri.toString()).append(" ====\n");
        while (true) {
            String line = logLines.pollFirst();
            if (line == null) {
                break;
            }
            logsAggregate.append(line + "\n");
        }
        if (logLines.size() > 0) {
            logger.warn("Log buffer was not fully drained for URI: {}", uri);
        }
        if (logger.isTraceEnabled()) {
            logger.trace("Downloaded log: {}.", logsAggregate);
        }
        return logsAggregate;
    } catch (IOException e) {
        throw new TransferException("Could not obtain log file: " + uri.toString(), e);
    }
}