Java Code Examples for java.util.Deque#isEmpty()
The following examples show how to use
java.util.Deque#isEmpty() .
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: Graph.java From openjdk-jdk9 with GNU General Public License v2.0 | 6 votes |
/** * Returns all nodes reachable from the given set of roots. */ public Set<T> dfs(Set<T> roots) { Deque<T> deque = new LinkedList<>(roots); Set<T> visited = new HashSet<>(); while (!deque.isEmpty()) { T u = deque.pop(); if (!visited.contains(u)) { visited.add(u); if (contains(u)) { adjacentNodes(u).stream() .filter(v -> !visited.contains(v)) .forEach(deque::push); } } } return visited; }
Example 2
Source File: TopologicalSort.java From interview with Apache License 2.0 | 6 votes |
public static void main(String args[]){ Graph<Integer> graph = new Graph<>(true); graph.addEdge(1, 3); graph.addEdge(1, 2); graph.addEdge(3, 4); graph.addEdge(5, 6); graph.addEdge(6, 3); graph.addEdge(3, 8); graph.addEdge(8, 11); TopologicalSort<Integer> sort = new TopologicalSort<Integer>(); Deque<Vertex<Integer>> result = sort.topSort(graph); while(!result.isEmpty()){ System.out.println(result.poll()); } }
Example 3
Source File: ReconstructItinerary.java From LeetCode-Sol-Res with MIT License | 6 votes |
public List<String> findItinerary(String[][] tickets) { Map<String, PriorityQueue<String>> g = new HashMap<>(); for (String[] t : tickets) { g.computeIfAbsent(t[0], k -> new PriorityQueue<>()).add(t[1]); } Deque<String> stack = new ArrayDeque<>(); LinkedList<String> route = new LinkedList<>(); stack.push("JFK"); while (!stack.isEmpty()) { while (g.containsKey(stack.peek()) && !g.get(stack.peek()).isEmpty()) { stack.push(g.get(stack.peek()).poll()); } route.addFirst(stack.pop()); } return route; }
Example 4
Source File: CFRDecompiler.java From bytecode-viewer with GNU General Public License v3.0 | 5 votes |
@SuppressWarnings("resource") public void zip(File directory, File zipfile) throws IOException { java.net.URI base = directory.toURI(); Deque<File> queue = new LinkedList<File>(); queue.push(directory); OutputStream out = new FileOutputStream(zipfile); Closeable res = out; try { ZipOutputStream zout = new ZipOutputStream(out); res = zout; while (!queue.isEmpty()) { directory = queue.pop(); for (File kid : directory.listFiles()) { String name = base.relativize(kid.toURI()).getPath(); if (kid.isDirectory()) { queue.push(kid); name = name.endsWith("/") ? name : name + "/"; zout.putNextEntry(new ZipEntry(name)); } else { zout.putNextEntry(new ZipEntry(name)); copy(kid, zout); zout.closeEntry(); } } } } finally { res.close(); out.close(); } }
Example 5
Source File: Log4jServiceActivator.java From wildfly-core with GNU Lesser General Public License v2.1 | 5 votes |
private String getFirstValue(final Map<String, Deque<String>> params, final String key) { if (params.containsKey(key)) { final Deque<String> values = params.get(key); if (values != null && !values.isEmpty()) { return values.getFirst(); } } return null; }
Example 6
Source File: Types.java From ProjectAres with GNU Affero General Public License v3.0 | 5 votes |
public static @Nullable Class<?> findAncestor(Class<?> type, java.util.function.Predicate<Class<?>> pred) { Deque<Class<?>> queue = new ArrayDeque<>(); queue.add(type); while(!queue.isEmpty()) { final Class<?> t = queue.remove(); if(pred.test(t)) return t; if(t.getSuperclass() != null) { queue.add(t.getSuperclass()); } Collections.addAll(queue, t.getInterfaces()); } return null; }
Example 7
Source File: InferredModelAssociator.java From dsl-devkit with Eclipse Public License 1.0 | 5 votes |
/** {@inheritDoc} */ @Override public EObject getPrimarySourceModelElement(final EObject inferredModelElement) { if (inferredModelElement == null) { return null; } Map<EObject, Deque<EObject>> map = getInferredModelToSourceMap(inferredModelElement.eResource()); Deque<EObject> result = map.get(inferredModelElement); return result != null && !result.isEmpty() ? result.getFirst() : null; }
Example 8
Source File: ButterKnifeProcessor.java From butterknife with Apache License 2.0 | 5 votes |
private Map<TypeElement, ClasspathBindingSet> findAllSupertypeBindings( Map<TypeElement, BindingSet.Builder> builderMap, Set<TypeElement> processedInThisRound) { Map<TypeElement, ClasspathBindingSet> classpathBindings = new HashMap<>(); Set<Class<? extends Annotation>> supportedAnnotations = getSupportedAnnotations(); Set<Class<? extends Annotation>> requireViewInConstructor = ImmutableSet.<Class<? extends Annotation>>builder() .addAll(LISTENERS).add(BindView.class).add(BindViews.class).build(); supportedAnnotations.removeAll(requireViewInConstructor); for (TypeElement typeElement : builderMap.keySet()) { // Make sure to process superclass before subclass. This is because if there is a class that // requires a View in the constructor, all subclasses need it as well. Deque<TypeElement> superClasses = new ArrayDeque<>(); TypeElement superClass = getSuperClass(typeElement); while (superClass != null && !processedInThisRound.contains(superClass) && !classpathBindings.containsKey(superClass)) { superClasses.addFirst(superClass); superClass = getSuperClass(superClass); } boolean parentHasConstructorWithView = false; while (!superClasses.isEmpty()) { TypeElement superclass = superClasses.removeFirst(); ClasspathBindingSet classpathBinding = findBindingInfoForType(superclass, requireViewInConstructor, supportedAnnotations, parentHasConstructorWithView); if (classpathBinding != null) { parentHasConstructorWithView |= classpathBinding.constructorNeedsView(); classpathBindings.put(superclass, classpathBinding); } } } return ImmutableMap.copyOf(classpathBindings); }
Example 9
Source File: Asteroids.java From LeetCode-Sol-Res with MIT License | 5 votes |
/** * O(n) Time, O(n) Space. * Keep track of collisions using a Stack (represented by Deque in Java). * For each asteroid, ast: * | If stack is not empty, asteroid size < 0, and previous asteroid size > 0 * | Deal with collision. * | Else, no collision, just add to stack. * After all asteroids are done, convert the resulting stack to an array. */ public int[] asteroidCollision(int[] asteroids) { Deque<Integer> stack = new ArrayDeque<>(); for (int ast : asteroids) { if (!stack.isEmpty() && ast < 0 && 0 < stack.peek()) { collide(stack, ast); } else { stack.push(ast); } } return stackToArray(stack); }
Example 10
Source File: TemplateResolver.java From poi-tl with Apache License 2.0 | 5 votes |
private void resolveXWPFRuns(List<XWPFRun> runs, final List<MetaTemplate> metaTemplates, final Deque<BlockTemplate> stack) { for (XWPFRun run : runs) { String text = null; if (null == run || StringUtils.isBlank(text = run.getText(0))) continue; RunTemplate runTemplate = parseTemplateFactory(text, run); if (null == runTemplate) continue; char charValue = runTemplate.getSign().charValue(); if (charValue == config.getIterable().getLeft()) { IterableTemplate freshIterableTemplate = new IterableTemplate(runTemplate); stack.push(freshIterableTemplate); } else if (charValue == config.getIterable().getRight()) { if (stack.isEmpty()) throw new ResolverException( "Mismatched start/end tags: No start mark found for end mark " + runTemplate); BlockTemplate latestIterableTemplate = stack.pop(); if (StringUtils.isNotEmpty(runTemplate.getTagName()) && !latestIterableTemplate.getStartMark().getTagName().equals(runTemplate.getTagName())) { throw new ResolverException("Mismatched start/end tags: start mark " + latestIterableTemplate.getStartMark() + " does not match to end mark " + runTemplate); } latestIterableTemplate.setEndMark(runTemplate); if (latestIterableTemplate instanceof IterableTemplate) { latestIterableTemplate = ((IterableTemplate) latestIterableTemplate).buildIfInline(); } if (stack.isEmpty()) { metaTemplates.add(latestIterableTemplate); } else { stack.peek().getTemplates().add(latestIterableTemplate); } } else { if (stack.isEmpty()) { metaTemplates.add(runTemplate); } else { stack.peek().getTemplates().add(runTemplate); } } } }
Example 11
Source File: Solution.java From daily-coding-problems with Apache License 2.0 | 5 votes |
int getLevelWithMinimumSum(TreeNode<Integer> root) { if (root == null) { return -1; } Deque<TreeNode<Integer>> queue = new ArrayDeque<>(); int minSum = Integer.MAX_VALUE; int minLevel = -1; int currentSum = 0; int level = 0; queue.offer(root); TreeNode<Integer> dummy = new TreeNode<>(0); queue.offer(dummy); while (!queue.isEmpty()) { TreeNode<Integer> current = queue.removeFirst(); if (current == dummy) { if (currentSum < minSum) { minSum = currentSum; minLevel = level; } if (!queue.isEmpty()) { queue.offer(dummy); } level++; currentSum = 0; } else { currentSum += current.getData(); if (current.getLeft() != null) { queue.offer(current.getLeft()); } if (current.getRight() != null) { queue.offer(current.getRight()); } } } return minLevel; }
Example 12
Source File: Runtime.java From PCDP with Eclipse Public License 1.0 | 5 votes |
/** * Get the current task of the current thread. * @return Currently executing task. */ public static BaseTask currentTask() { final Deque<BaseTask> taskStack = Runtime.threadLocalTaskStack.get(); if (taskStack.isEmpty()) { return null; } else { return taskStack.peek(); } }
Example 13
Source File: ComposedRunnerJobFactory.java From composed-task-runner with Apache License 2.0 | 5 votes |
private void handleTransition(Deque<Flow> resultFlowDeque, TaskAppNode taskAppNode) { String beanName = getBeanName(taskAppNode); Step currentStep = this.context.getBean(beanName, Step.class); FlowBuilder<Flow> builder = new FlowBuilder<Flow>(beanName) .from(currentStep); boolean wildCardPresent = false; for (TransitionNode transitionNode : taskAppNode.getTransitions()) { String transitionBeanName = getBeanName(transitionNode); wildCardPresent = transitionNode.getStatusToCheck().equals(WILD_CARD); Step transitionStep = this.context.getBean(transitionBeanName, Step.class); builder.on(transitionNode.getStatusToCheck()).to(transitionStep) .from(currentStep); } if (wildCardPresent && !resultFlowDeque.isEmpty()) { throw new IllegalStateException( "Invalid flow following '*' specifier."); } else { //if there are nodes are in the execution Deque. Make sure that //they are processed as a target of the wildcard instead of the //whole transition. if (!resultFlowDeque.isEmpty()) { builder.on(WILD_CARD).to(handleFlowForSegment(resultFlowDeque)).from(currentStep); } } resultFlowDeque.push(builder.end()); }
Example 14
Source File: Solution2.java From LeetCode-Solution-in-Good-Style with Apache License 2.0 | 5 votes |
public String removeKdigits(String num, int k) { int len = num.length(); if (len == k) { return "0"; } int remaining = len - k; char[] charArray = num.toCharArray(); Deque<Character> stack = new ArrayDeque<>(); for (char c : charArray) { while (k > 0 && !stack.isEmpty() && stack.peekLast() > c) { stack.removeLast(); k--; } stack.addLast(c); } // System.out.println(stack); // 只取前面剩下的部分,针对 String num = "112"; int k = 1; 这种用例 while (stack.size() > remaining) { stack.pollLast(); } while (!stack.isEmpty() && stack.peekFirst() == '0') { stack.removeFirst(); } if (stack.isEmpty()) { return "0"; } return toString(stack); }
Example 15
Source File: RecursiveObjectLeaker.java From yangtools with Eclipse Public License 1.0 | 5 votes |
public static void afterConstructor(final Object key) { final Deque<Entry<?, Object>> stack = STACK.get(); checkState(stack != null, "No stack allocated when completing %s", key); final Entry<?, Object> top = stack.pop(); if (stack.isEmpty()) { LOG.trace("Removed empty thread stack"); STACK.set(null); } checkState(key == top.getKey(), "Expected key %s, have %s", top.getKey(), key); checkState(top.getValue() != null, ""); }
Example 16
Source File: SpliteratorCollisions.java From openjdk-jdk8u with GNU General Public License v2.0 | 4 votes |
private static <T> void testSplitUntilNull(SplitNode<T> e) { // Use an explicit stack to avoid a StackOverflowException when testing a Spliterator // that when repeatedly split produces a right-balanced (and maybe degenerate) tree, or // for a spliterator that is badly behaved. Deque<SplitNode<T>> stack = new ArrayDeque<>(); stack.push(e); int iteration = 0; while (!stack.isEmpty()) { assertTrue(iteration++ < MAXIMUM_STACK_CAPACITY, "Exceeded maximum stack modification count of 1 << 18"); e = stack.pop(); Spliterator<T> parentAndRightSplit = e.s; long parentEstimateSize = parentAndRightSplit.estimateSize(); assertTrue(parentEstimateSize >= 0, String.format("Split size estimate %d < 0", parentEstimateSize)); long parentSize = parentAndRightSplit.getExactSizeIfKnown(); Spliterator<T> leftSplit = parentAndRightSplit.trySplit(); if (leftSplit == null) { parentAndRightSplit.forEachRemaining(e.c); continue; } assertSpliterator(leftSplit, e.rootCharacteristics); assertSpliterator(parentAndRightSplit, e.rootCharacteristics); if (parentEstimateSize != Long.MAX_VALUE && leftSplit.estimateSize() > 0 && parentAndRightSplit.estimateSize() > 0) { assertTrue(leftSplit.estimateSize() < parentEstimateSize, String.format("Left split size estimate %d >= parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize)); assertTrue(parentAndRightSplit.estimateSize() < parentEstimateSize, String.format("Right split size estimate %d >= parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize)); } else { assertTrue(leftSplit.estimateSize() <= parentEstimateSize, String.format("Left split size estimate %d > parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize)); assertTrue(parentAndRightSplit.estimateSize() <= parentEstimateSize, String.format("Right split size estimate %d > parent split size estimate %d", leftSplit.estimateSize(), parentEstimateSize)); } long leftSize = leftSplit.getExactSizeIfKnown(); long rightSize = parentAndRightSplit.getExactSizeIfKnown(); if (parentSize >= 0 && leftSize >= 0 && rightSize >= 0) assertEquals(parentSize, leftSize + rightSize, String.format("exact left split size %d + exact right split size %d != parent exact split size %d", leftSize, rightSize, parentSize)); // Add right side to stack first so left side is popped off first stack.push(e.fromSplit(parentAndRightSplit)); stack.push(e.fromSplit(leftSplit)); } }
Example 17
Source File: ReportAnalyzer.java From quarkus with Apache License 2.0 | 4 votes |
/** * Analyze the contents of the call tree report produced by Substrate when using -H:+PrintAnalysisCallTree, * and does a more meaningful analysis of what is causing a type to be retained. * * In particular for virtual or interface methods that have multiple implementations what is calling this method * is not really important, its what caused this particular instance of the class to be created that is important * (e.g. if you have an instance of Runnable, you don't care about all the different parts that call runnable, you * care about what created this particular instance). * * If a virtual or interface call is detected with multiple implementations then printing the current call flow * is abandoned, and instead the call flow for the constructor of the current object is printed instead. * */ public String analyse(String className, String methodName) throws Exception { List<Node> dm = byClassMap.getOrDefault(className, new ArrayList<>()).stream() .filter((s) -> s.method.startsWith(methodName + "(")).collect(Collectors.toList()); Deque<Node> runQueue = new ArrayDeque<>(dm); Set<String> attemptedClasses = new HashSet<>(); if (methodName.equals("<init>")) { attemptedClasses.add(className); } StringBuilder ret = new StringBuilder(); StringBuilder sb = new StringBuilder(); while (!runQueue.isEmpty()) { Node current = runQueue.pop(); sb.append("Possible path to " + current.className + "." + current.method + "\n"); while (current != null) { sb.append("\t" + current.className + "." + current.method + '\n'); String reason = null; if (current.parent == null || current.parent.children.size() > 1) { if (current.type.equals("is overridden by")) { reason = "This is an implementation of " + current.parent.className + " printing path to constructors of " + current.className + "\n"; } else if (current.type.equals("is implemented by")) { reason = "This is an implementation of " + current.parent.className + " printing path to constructors of " + current.className + "\n"; } } if (reason != null) { if (!attemptedClasses.contains(current.className)) { attemptedClasses.add(current.className); List<Node> toAdd = constructors.getOrDefault(current.className, new ArrayList<>()); runQueue.addAll(toAdd); sb.append(reason + '\n'); sb.append("\n"); ret.append(sb); } //note that we discard the string builder if it is part of attemptedClasses, as this basically //represents an alternate path that we have already displayed sb.setLength(0); break; } current = current.parent; } } ret.append(sb); return ret.toString(); }
Example 18
Source File: JavaInputAstVisitor.java From javaide with GNU General Public License v3.0 | 4 votes |
private List<Op> visitModifiers( List<? extends AnnotationTree> annotationTrees, Direction annotationsDirection, Optional<BreakTag> declarationAnnotationBreak) { if (annotationTrees.isEmpty() && !nextIsModifier()) { return EMPTY_LIST; } Deque<AnnotationTree> annotations = new ArrayDeque<>(annotationTrees); builder.open(ZERO); boolean first = true; boolean lastWasAnnotation = false; while (!annotations.isEmpty()) { if (nextIsModifier()) { break; } if (!first) { builder.addAll( annotationsDirection.isVertical() ? forceBreakList(declarationAnnotationBreak) : breakList(declarationAnnotationBreak)); } scan(annotations.removeFirst(), null); first = false; lastWasAnnotation = true; } builder.close(); ImmutableList<Op> trailingBreak = annotationsDirection.isVertical() ? forceBreakList(declarationAnnotationBreak) : breakList(declarationAnnotationBreak); if (annotations.isEmpty() && !nextIsModifier()) { return trailingBreak; } if (lastWasAnnotation) { builder.addAll(trailingBreak); } builder.open(ZERO); first = true; while (nextIsModifier() || !annotations.isEmpty()) { if (!first) { builder.addAll(breakFillList(Optional.<BreakTag>absent())); } if (nextIsModifier()) { token(builder.peekToken().get()); } else { scan(annotations.removeFirst(), null); lastWasAnnotation = true; } first = false; } builder.close(); return breakFillList(Optional.<BreakTag>absent()); }
Example 19
Source File: JavaInputAstVisitor.java From java-n-IDE-for-Android with Apache License 2.0 | 4 votes |
private List<Op> visitModifiers( List<? extends AnnotationTree> annotationTrees, Direction annotationsDirection, Optional<BreakTag> declarationAnnotationBreak) { if (annotationTrees.isEmpty() && !nextIsModifier()) { return EMPTY_LIST; } Deque<AnnotationTree> annotations = new ArrayDeque<>(annotationTrees); builder.open(ZERO); boolean first = true; boolean lastWasAnnotation = false; while (!annotations.isEmpty()) { if (nextIsModifier()) { break; } if (!first) { builder.addAll( annotationsDirection.isVertical() ? forceBreakList(declarationAnnotationBreak) : breakList(declarationAnnotationBreak)); } scan(annotations.removeFirst(), null); first = false; lastWasAnnotation = true; } builder.close(); ImmutableList<Op> trailingBreak = annotationsDirection.isVertical() ? forceBreakList(declarationAnnotationBreak) : breakList(declarationAnnotationBreak); if (annotations.isEmpty() && !nextIsModifier()) { return trailingBreak; } if (lastWasAnnotation) { builder.addAll(trailingBreak); } builder.open(ZERO); first = true; while (nextIsModifier() || !annotations.isEmpty()) { if (!first) { builder.addAll(breakFillList(Optional.<BreakTag>absent())); } if (nextIsModifier()) { token(builder.peekToken().get()); } else { scan(annotations.removeFirst(), null); lastWasAnnotation = true; } first = false; } builder.close(); return breakFillList(Optional.<BreakTag>absent()); }
Example 20
Source File: SentinelZuulPreFilter.java From Sentinel with Apache License 2.0 | 4 votes |
@Override public Object run() throws ZuulException { RequestContext ctx = RequestContext.getCurrentContext(); String origin = parseOrigin(ctx.getRequest()); String routeId = (String)ctx.get(ZuulConstant.PROXY_ID_KEY); Deque<EntryHolder> holders = new ArrayDeque<>(); String fallBackRoute = routeId; try { if (StringUtil.isNotBlank(routeId)) { ContextUtil.enter(GATEWAY_CONTEXT_ROUTE_PREFIX + routeId, origin); doSentinelEntry(routeId, RESOURCE_MODE_ROUTE_ID, ctx, holders); } Set<String> matchingApis = pickMatchingApiDefinitions(ctx); if (!matchingApis.isEmpty() && ContextUtil.getContext() == null) { ContextUtil.enter(ZuulConstant.ZUUL_DEFAULT_CONTEXT, origin); } for (String apiName : matchingApis) { fallBackRoute = apiName; doSentinelEntry(apiName, RESOURCE_MODE_CUSTOM_API_NAME, ctx, holders); } } catch (BlockException ex) { ZuulBlockFallbackProvider zuulBlockFallbackProvider = ZuulBlockFallbackManager.getFallbackProvider( fallBackRoute); BlockResponse blockResponse = zuulBlockFallbackProvider.fallbackResponse(fallBackRoute, ex); // Prevent routing from running ctx.setRouteHost(null); ctx.set(ZuulConstant.SERVICE_ID_KEY, null); // Set fallback response. ctx.setResponseBody(blockResponse.toString()); ctx.setResponseStatusCode(blockResponse.getCode()); // Set Response ContentType ctx.getResponse().setContentType("application/json; charset=utf-8"); } finally { // We don't exit the entry here. We need to exit the entries in post filter to record Rt correctly. // So here the entries will be carried in the request context. if (!holders.isEmpty()) { ctx.put(ZuulConstant.ZUUL_CTX_SENTINEL_ENTRIES_KEY, holders); } } return null; }