Java Code Examples for java.util.Deque#addFirst()

The following examples show how to use java.util.Deque#addFirst() . You can vote up the ones you like or vote down the ones you don't like, and go to the original project or source file by following the links above each example. You may check out the related API usage on the sidebar.
Example 1
Source File: UnreachableCodeEliminator.java    From JAADAS with GNU General Public License v3.0 6 votes vote down vote up
private <T> Set<T> reachable(T first, DirectedGraph<T> g) {
	if ( first == null || g == null ) {
		return Collections.<T>emptySet();
	}
	Set<T> visited = new HashSet<T>(g.size());
	Deque<T> q = new ArrayDeque<T>();
	q.addFirst(first);
	do {
		T t = q.removeFirst();
		if ( visited.add(t) ) {				
			q.addAll(g.getSuccsOf(t));
		}
	}
	while (!q.isEmpty());
	
	return visited;
}
 
Example 2
Source File: DimensionHelpers.java    From google-java-format with Apache License 2.0 6 votes vote down vote up
/**
 * Accumulates a flattened list of array dimensions specifiers with type annotations, and returns
 * the base type.
 *
 * <p>Given {@code int @A @B [][] @C []}, adds {@code [[@A, @B], [@C]]} to dims and returns {@code
 * int}.
 */
private static Tree extractDims(Deque<List<AnnotationTree>> dims, Tree node) {
  switch (node.getKind()) {
    case ARRAY_TYPE:
      return extractDims(dims, ((ArrayTypeTree) node).getType());
    case ANNOTATED_TYPE:
      AnnotatedTypeTree annotatedTypeTree = (AnnotatedTypeTree) node;
      if (annotatedTypeTree.getUnderlyingType().getKind() != Tree.Kind.ARRAY_TYPE) {
        return node;
      }
      node = extractDims(dims, annotatedTypeTree.getUnderlyingType());
      dims.addFirst(ImmutableList.copyOf(annotatedTypeTree.getAnnotations()));
      return node;
    default:
      return node;
  }
}
 
Example 3
Source File: TreeTraversals.java    From interview with Apache License 2.0 6 votes vote down vote up
public void postOrderItrOneStack(Node root){
    Node current = root;
    Deque<Node> stack = new LinkedList<>();
    while(current != null || !stack.isEmpty()){
        if(current != null){
            stack.addFirst(current);
            current = current.left;
        }else{
            Node temp = stack.peek().right;
            if (temp == null) {
                temp = stack.poll();
                System.out.print(temp.data + " ");
                while (!stack.isEmpty() && temp == stack.peek().right) {
                    temp = stack.poll();
                    System.out.print(temp.data + " ");
                }
            } else {
                current = temp;
            }
        }
    }
}
 
Example 4
Source File: Nodes.java    From jdk1.8-source-analysis with Apache License 2.0 6 votes vote down vote up
/**
 * Depth first search, in left-to-right order, of the node tree, using
 * an explicit stack, to find the next non-empty leaf node.
 */
@SuppressWarnings("unchecked")
protected final N findNextLeafNode(Deque<N> stack) {
    N n = null;
    while ((n = stack.pollFirst()) != null) {
        if (n.getChildCount() == 0) {
            if (n.count() > 0)
                return n;
        } else {
            for (int i = n.getChildCount() - 1; i >= 0; i--)
                stack.addFirst((N) n.getChild(i));
        }
    }

    return null;
}
 
Example 5
Source File: DefaultJavaPackageFinder.java    From buck with Apache License 2.0 6 votes vote down vote up
@Override
public Path findJavaPackageFolder(Path pathRelativeToProjectRoot) {
  for (String pathFromRoot : pathsFromRoot) {
    if (pathRelativeToProjectRoot.startsWith(pathFromRoot)) {
      return MorePaths.getParentOrEmpty(
          MorePaths.relativize(
              pathRelativeToProjectRoot.getFileSystem().getPath(pathFromRoot),
              pathRelativeToProjectRoot));
    }
  }

  Path directory = pathRelativeToProjectRoot.getParent();
  Deque<String> parts = new LinkedList<>();
  while (directory != null && !pathElements.contains(directory.getFileName().toString())) {
    parts.addFirst(directory.getFileName().toString());
    directory = directory.getParent();
  }

  if (!parts.isEmpty()) {
    return pathRelativeToProjectRoot
        .getFileSystem()
        .getPath(Joiner.on(File.separatorChar).join(parts));
  } else {
    return pathRelativeToProjectRoot.getFileSystem().getPath("");
  }
}
 
Example 6
Source File: Ofdpa2GroupHandler.java    From onos with Apache License 2.0 6 votes vote down vote up
/**
 * Creates a simple L2 Interface Group.
 * @param nextObj the next Objective
 */
private void createL2InterfaceGroup(NextObjective nextObj) {
    VlanId assignedVlan = readVlanFromSelector(nextObj.meta());
    if (assignedVlan == null) {
        log.warn("VLAN ID required by simple next obj is missing. Abort.");
        fail(nextObj, ObjectiveError.BADPARAMS);
        return;
    }
    List<GroupInfo> groupInfos = prepareL2InterfaceGroup(nextObj, assignedVlan);
    // There is only one L2 interface group in this case
    GroupDescription l2InterfaceGroupDesc = groupInfos.get(0).innerMostGroupDesc();
    // Put all dependency information into allGroupKeys
    List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
    Deque<GroupKey> gkeyChain = new ArrayDeque<>();
    gkeyChain.addFirst(l2InterfaceGroupDesc.appCookie());
    allGroupKeys.add(gkeyChain);
    // Point the next objective to this group
    OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObj);
    updatePendingNextObjective(l2InterfaceGroupDesc.appCookie(), ofdpaGrp);
    // Start installing the inner-most group
    groupService.addGroup(l2InterfaceGroupDesc);    }
 
Example 7
Source File: State.java    From ZXing-Orient with Apache License 2.0 5 votes vote down vote up
BitArray toBitArray(byte[] text) {
  // Reverse the tokens, so that they are in the order that they should
  // be output
  Deque<Token> symbols = new LinkedList<>();
  for (Token token = endBinaryShift(text.length).token; token != null; token = token.getPrevious()) {
    symbols.addFirst(token);
  }
  BitArray bitArray = new BitArray();
  // Add each token to the result.
  for (Token symbol : symbols) {
    symbol.appendTo(bitArray, text);
  }
  //assert bitArray.getSize() == this.bitCount;
  return bitArray;
}
 
Example 8
Source File: AbstractClusterStory.java    From RDFS with Apache License 2.0 5 votes vote down vote up
protected synchronized void parseTopologyTree() {
  if (machineNodes == null) {
    Node root = getClusterTopology();
    SortedSet<MachineNode> mNodes = new TreeSet<MachineNode>();
    SortedSet<RackNode> rNodes = new TreeSet<RackNode>();
    // dfs search of the tree.
    Deque<Node> unvisited = new ArrayDeque<Node>();
    Deque<Integer> distUnvisited = new ArrayDeque<Integer>();
    unvisited.add(root);
    distUnvisited.add(0);
    for (Node n = unvisited.poll(); n != null; n = unvisited.poll()) {
      int distance = distUnvisited.poll();
      if (n instanceof RackNode) {
        rNodes.add((RackNode) n);
        mNodes.addAll(((RackNode) n).getMachinesInRack());
        if (distance + 1 > maximumDistance) {
          maximumDistance = distance + 1;
        }
      } else if (n instanceof MachineNode) {
        mNodes.add((MachineNode) n);
        if (distance > maximumDistance) {
          maximumDistance = distance;
        }
      } else {
        for (Node child : n.getChildren()) {
          unvisited.addFirst(child);
          distUnvisited.addFirst(distance+1);
        }
      }
    }

    machineNodes = Collections.unmodifiableSortedSet(mNodes);
    rackNodes = Collections.unmodifiableSortedSet(rNodes);
  }
}
 
Example 9
Source File: Nodes.java    From Bytecoder with Apache License 2.0 5 votes vote down vote up
/**
 * Initiate a stack containing, in left-to-right order, the child nodes
 * covered by this spliterator
 */
@SuppressWarnings("unchecked")
protected final Deque<N> initStack() {
    // Bias size to the case where leaf nodes are close to this node
    // 8 is the minimum initial capacity for the ArrayDeque implementation
    Deque<N> stack = new ArrayDeque<>(8);
    for (int i = curNode.getChildCount() - 1; i >= curChildIndex; i--)
        stack.addFirst((N) curNode.getChild(i));
    return stack;
}
 
Example 10
Source File: ConsString.java    From openjdk-8-source with GNU General Public License v2.0 5 votes vote down vote up
private void flatten() {
    // We use iterative traversal as recursion may exceed the stack size limit.
    final char[] chars = new char[length];
    int pos = length;
    // Strings are most often composed by appending to the end, which causes ConsStrings
    // to be very unbalanced, with mostly single string elements on the right and a long
    // linear list on the left. Traversing from right to left helps to keep the stack small
    // in this scenario.
    final Deque<CharSequence> stack = new ArrayDeque<>();
    stack.addFirst(left);
    CharSequence cs = right;

    do {
        if (cs instanceof ConsString) {
            final ConsString cons = (ConsString) cs;
            stack.addFirst(cons.left);
            cs = cons.right;
        } else {
            final String str = (String) cs;
            pos -= str.length();
            str.getChars(0, str.length(), chars, pos);
            cs = stack.isEmpty() ? null : stack.pollFirst();
        }
    } while (cs != null);

    left = new String(chars);
    right = "";
    flat = true;
}
 
Example 11
Source File: AddAndRemoveOnListAdapterOutsideOfJavaScriptContextTest.java    From openjdk-jdk8u-backup with GNU General Public License v2.0 5 votes vote down vote up
@Test
public void testUnshift() throws ScriptException {
    final Deque<Object> l = getListAdapter();
    l.addFirst(0);
    assertEquals(l.getFirst(), 0);
    assertEquals(l.getLast(), 4);
    assertEquals(l.size(), 5);
}
 
Example 12
Source File: ConsString.java    From jdk8u60 with GNU General Public License v2.0 5 votes vote down vote up
private synchronized void flatten(final boolean flattenNested) {
    // We use iterative traversal as recursion may exceed the stack size limit.
    final char[] chars = new char[length];
    int pos = length;
    // Strings are most often composed by appending to the end, which causes ConsStrings
    // to be very unbalanced, with mostly single string elements on the right and a long
    // linear list on the left. Traversing from right to left helps to keep the stack small
    // in this scenario.
    final Deque<CharSequence> stack = new ArrayDeque<>();
    stack.addFirst(left);
    CharSequence cs = right;

    do {
        if (cs instanceof ConsString) {
            final ConsString cons = (ConsString) cs;
            // Count the times a cons-string is traversed as part of other cons-strings being flattened.
            // If it crosses a threshold we flatten the nested cons-string internally.
            if (cons.state == STATE_FLATTENED || (flattenNested && ++cons.state >= STATE_THRESHOLD)) {
                cs = cons.flattened(false);
            } else {
                stack.addFirst(cons.left);
                cs = cons.right;
            }
        } else {
            final String str = (String) cs;
            pos -= str.length();
            str.getChars(0, str.length(), chars, pos);
            cs = stack.isEmpty() ? null : stack.pollFirst();
        }
    } while (cs != null);

    left = new String(chars);
    right = "";
    state = STATE_FLATTENED;
}
 
Example 13
Source File: Nodes.java    From Java8CN with Apache License 2.0 5 votes vote down vote up
/**
 * Initiate a stack containing, in left-to-right order, the child nodes
 * covered by this spliterator
 */
@SuppressWarnings("unchecked")
protected final Deque<N> initStack() {
    // Bias size to the case where leaf nodes are close to this node
    // 8 is the minimum initial capacity for the ArrayDeque implementation
    Deque<N> stack = new ArrayDeque<>(8);
    for (int i = curNode.getChildCount() - 1; i >= curChildIndex; i--)
        stack.addFirst((N) curNode.getChild(i));
    return stack;
}
 
Example 14
Source File: Nodes.java    From openjdk-jdk9 with GNU General Public License v2.0 5 votes vote down vote up
/**
 * Initiate a stack containing, in left-to-right order, the child nodes
 * covered by this spliterator
 */
@SuppressWarnings("unchecked")
protected final Deque<N> initStack() {
    // Bias size to the case where leaf nodes are close to this node
    // 8 is the minimum initial capacity for the ArrayDeque implementation
    Deque<N> stack = new ArrayDeque<>(8);
    for (int i = curNode.getChildCount() - 1; i >= curChildIndex; i--)
        stack.addFirst((N) curNode.getChild(i));
    return stack;
}
 
Example 15
Source File: Collections2Test.java    From j2objc with Apache License 2.0 5 votes vote down vote up
public void test_Queue_forEach() {
    Deque<Integer> deque = new ArrayDeque<Integer>();
    deque.addFirst(2);
    deque.addFirst(1);
    deque.addFirst(0);

    Queue<Integer> queue = Collections.asLifoQueue(deque);
    ArrayList<Integer> output = new ArrayList<Integer>();
    queue.forEach(v -> output.add(v));

    assertEquals(3, output.size());
    assertEquals(0, (int)output.get(0));
    assertEquals(1, (int)output.get(1));
    assertEquals(2, (int)output.get(2));
}
 
Example 16
Source File: SkyQueryUtils.java    From bazel with Apache License 2.0 5 votes vote down vote up
/**
 * Gets a path from {@code from} to {@code to}, walking the graph revealed by {@code getFwdDeps}.
 *
 * <p>In case the type {@link T} does not implement equality, {@code label} will be used to map
 * elements of type {@link T} to elements of type {@link L} which does implement equality. {@code
 * label} should be an injective function. For instance, if {@link T} is of type {@link Target}
 * then {@link L} could be of type {@link Label} and {@code label} could be {@link
 * Target::getLabel}.
 *
 * <p>Implemented with a breadth-first search.
 */
static <T, L> ImmutableList<T> getNodesOnPath(
    T from, T to, GetFwdDeps<T> getFwdDeps, Function<T, L> label) throws InterruptedException {
  // Tree of nodes visited so far.
  Map<L, L> nodeToParent = new HashMap<>();
  Map<L, T> labelToTarget = new HashMap<>();
  // Contains all nodes left to visit in a (LIFO) stack.
  Deque<T> toVisit = new ArrayDeque<>();
  toVisit.add(from);
  nodeToParent.put(label.apply(from), null);
  labelToTarget.put(label.apply(from), from);
  while (!toVisit.isEmpty()) {
    T current = toVisit.removeFirst();
    if (label.apply(to).equals(label.apply(current))) {
      List<L> labelPath = Digraph.getPathToTreeNode(nodeToParent, label.apply(to));
      ImmutableList.Builder<T> targetPathBuilder = ImmutableList.builder();
      for (L item : labelPath) {
        targetPathBuilder.add(Preconditions.checkNotNull(labelToTarget.get(item), item));
      }
      return targetPathBuilder.build();
    }
    for (T dep : getFwdDeps.getFwdDeps(ImmutableList.of(current))) {
      L depLabel = label.apply(dep);
      if (!nodeToParent.containsKey(depLabel)) {
        nodeToParent.put(depLabel, label.apply(current));
        labelToTarget.put(depLabel, dep);
        toVisit.addFirst(dep);
      }
    }
  }
  // Note that the only current caller of this method checks first to see if there is a path
  // before calling this method. It is not clear what the return value should be here.
  return null;
}
 
Example 17
Source File: ScriptExecutionUtil.java    From bitcoin-transaction-explorer with MIT License 4 votes vote down vote up
private static void addStackObject(final Deque<StackObject> stack, final StackObject object) {
  stack.addFirst(object);
}
 
Example 18
Source File: Ofdpa2GroupHandler.java    From onos with Apache License 2.0 4 votes vote down vote up
protected void modifyBucketInL3Group(NextObjective nextObjective, NextGroup next) {

        //get l3 group
        GroupInfo groupInfo = prepareL3UnicastGroup(nextObjective, next);
        if (groupInfo == null) {
            log.warn("Null groupInfo retrieved for next obj. Abort.");
            fail(nextObjective, ObjectiveError.BADPARAMS);
            return;
        }

        GroupDescription l3UnicastGroupDesc = groupInfo.nextGroupDesc();

        // Replace group bucket for L3 UC interface group
        groupService.setBucketsForGroup(deviceId, l3UnicastGroupDesc.appCookie(),
                        l3UnicastGroupDesc.buckets(), l3UnicastGroupDesc.appCookie(),
                        l3UnicastGroupDesc.appId());

        // create object for local and distributed storage
        Deque<GroupKey> gkeyChain = new ArrayDeque<>();
        gkeyChain.addFirst(groupInfo.innerMostGroupDesc().appCookie());
        gkeyChain.addFirst(groupInfo.nextGroupDesc().appCookie());
        List<Deque<GroupKey>> allGroupKeys = Lists.newArrayList();
        allGroupKeys.add(gkeyChain);
        OfdpaNextGroup ofdpaGrp = new OfdpaNextGroup(allGroupKeys, nextObjective);
        // store l3groupkey with the ofdpaNextGroup for the nextObjective that depends on it
        updatePendingNextObjective(groupInfo.nextGroupDesc().appCookie(), ofdpaGrp);

        // update store - synchronize access as there may be multiple threads
        // trying to update bucket from the same group, each with its own
        // potentially stale copy of allActiveKeys
        synchronized (flowObjectiveStore) {

            List<Deque<GroupKey>> modifiedGroupKeys = Lists.newArrayList();
            ArrayDeque<GroupKey> top = new ArrayDeque<>();
            top.add(l3UnicastGroupDesc.appCookie());
            top.add(groupInfo.innerMostGroupDesc().appCookie()); //l2 group key
            modifiedGroupKeys.add(top);

            flowObjectiveStore.putNextGroup(nextObjective.id(),
                                            new OfdpaNextGroup(modifiedGroupKeys,
                                                               nextObjective));
        }
    }
 
Example 19
Source File: LinkedDequeTest.java    From concurrentlinkedhashmap with Apache License 2.0 4 votes vote down vote up
@Test(dataProvider = "warmedDeque", expectedExceptions = IllegalArgumentException.class)
public void addFirst_whenLinked(Deque<SimpleLinkedValue> deque) {
  deque.addFirst(deque.peek());
}
 
Example 20
Source File: MappingExpr.java    From spectator with Apache License 2.0 3 votes vote down vote up
/**
 * Helper to zero out a value if there is not a change. For a stack with {@code num v1 v2},
 * if {@code v1 == v2}, then push 0.0 otherwise push {@code num}.
 *
 * For some values placed in JMX they are not regularly updated in all circumstances and
 * reporting the same value for each polling iteration gives the false impression of activity
 * when there is none. A common example is timers with the metrics library where the reservoir
 * is not rescaled during a fetch.
 *
 * https://github.com/dropwizard/metrics/issues/1030
 *
 * This operator can be used in conjunction with the previous variables to zero out the
 * misleading snapshots based on the count. For example:
 *
 * <pre>
 *   {50thPercentile},{Count},{previous:Count},:if-changed
 * </pre>
 */
private static void ifChanged(Deque<Double> stack) {
  double v2 = stack.removeFirst();
  double v1 = stack.removeFirst();
  double num = stack.removeFirst();
  stack.addFirst((Double.compare(v1, v2) == 0) ? 0.0 : num);
}