Java Code Examples for java.util.Queue#offer()
The following examples show how to use
java.util.Queue#offer() .
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: PriorityQueueTest.java From blog with BSD 2-Clause "Simplified" License | 6 votes |
public static void main(String[] args) { Queue<String> q = new PriorityQueue<>(); q.offer("apple"); q.offer("pear"); q.offer("banana"); System.out.println(q.poll()); // apple System.out.println(q.poll()); // banana System.out.println(q.poll()); // pear System.out.println(q.poll()); // null,因为队列为空 PriorityQueue<Subject> priorityQueue = new PriorityQueue<Subject>(); priorityQueue.offer(new Subject(1, 88)); priorityQueue.offer(new Subject(1, 87)); priorityQueue.offer(new Subject(1, 90)); System.out.println(priorityQueue.poll()); System.out.println(priorityQueue.poll()); System.out.println(priorityQueue.poll()); }
Example 2
Source File: RxRingBuffer.java From rxjava-extras with Apache License 2.0 | 6 votes |
/** * * @param o the value to buffer * @throws MissingBackpressureException * if more onNext are sent than have been requested */ public void onNext(Object o) throws MissingBackpressureException { boolean iae = false; boolean mbe = false; synchronized (this) { Queue<Object> q = queue; if (q != null) { mbe = !q.offer(NotificationLite.next(o)); } else { iae = true; } } if (iae) { throw new IllegalStateException("This instance has been unsubscribed and the queue is no longer usable."); } if (mbe) { throw new MissingBackpressureException(); } }
Example 3
Source File: SerializeAndReconstructTree.java From Project with Apache License 2.0 | 6 votes |
public static Node reconByLevelString(String levelStr) { String[] values = levelStr.split("_"); int index = 0; Node head = generateNodeByString(values[index++]); Queue<Node> queue = new LinkedList<Node>(); if (head != null) { queue.offer(head); } Node node = null; while (!queue.isEmpty()) { node = queue.poll(); node.left = generateNodeByString(values[index++]); node.right = generateNodeByString(values[index++]); if (node.left != null) { queue.offer(node.left); } if (node.right != null) { queue.offer(node.right); } } return head; }
Example 4
Source File: ControlledChannelOperation.java From twister2 with Apache License 2.0 | 6 votes |
/** * Start receiving from the next receiveGroup * @param receiveGroup the next receiveGroup */ public void startGroup(int receiveGroup, int sendGroup, Map<Integer, Integer> expectedReceives) { receiveProgressTracker.switchGroup(receiveGroup); List<Integer> receiveExecs = receiveGroupsWorkers.get(receiveGroup); this.expectedReceivePerWorker = expectedReceives; currentReceives.clear(); for (int i = 0; i < receiveExecs.size(); i++) { int exec = receiveExecs.get(i); int expected = expectedReceives.get(exec); // we offer the buffer only if we are expecting some messages if (expected > 0) { Queue<DataBuffer> list = receiveBuffers.get(exec); // poll the free receive buffers and ad to the receive DataBuffer buffer = freeReceiveBuffers.poll(); if (buffer == null) { throw new RuntimeException("Buffer cannot be null"); } list.offer(buffer); } currentReceives.put(exec, 0); } }
Example 5
Source File: TreeTraversalLevelByLevel.java From interview with Apache License 2.0 | 6 votes |
/** * Use one queue and delimiter to print level by level */ public void levelByLevelOneQueueUsingDelimiter(Node root) { if (root == null) { return; } Queue<Node> q = new LinkedList<Node>(); q.offer(root); q.offer(null); while (!q.isEmpty()) { root = q.poll(); if (root != null) { System.out.print(root.data + " "); if (root.left != null) { q.offer(root.left); } if (root.right != null) { q.offer(root.right); } } else { if (!q.isEmpty()) { System.out.println(); q.offer(null); } } } }
Example 6
Source File: FoldableListLayout.java From FoldableLayout with Apache License 2.0 | 6 votes |
private void recycleAdapterView(FoldableItemLayout layout) { if (layout.getBaseLayout().getChildCount() == 0) { return; // Nothing to recycle } View view = layout.getBaseLayout().getChildAt(0); layout.getBaseLayout().removeAllViews(); Integer type = viewsTypesMap.remove(view); if (type != null) { Queue<View> cache = recycledViews.get(type); if (cache == null) { recycledViews.put(type, cache = new LinkedList<>()); } cache.offer(view); } }
Example 7
Source File: PXHierarchyListener.java From pixate-freestyle-android with Apache License 2.0 | 6 votes |
@SuppressWarnings({ "rawtypes" }) private void traverseFragmentChildren(Queue<View> views) { while (!views.isEmpty()) { View view = views.poll(); if (view instanceof AdapterView) { setAdapterProxy((AdapterView) view); } if (view instanceof ViewGroup) { ViewGroup group = (ViewGroup) view; int count = group.getChildCount(); for (int i = 0; i < count; i++) { views.offer(group.getChildAt(i)); } } } }
Example 8
Source File: TestPoll.java From xmnlp with Apache License 2.0 | 6 votes |
public static void main(String[] args) { Queue<String> queue = new LinkedList<String>(); queue.offer("Hello"); queue.offer("world!"); queue.offer("您好!"); System.out.println("使用offer()之后队列的长度:" + queue.size()); System.out.println("使用peek()取出第一个元素: " + queue.peek()); System.out.println("使用element()取出第一个元素: " + queue.element()); System.out.println("使用peek/element之后队列的长度: " + queue.size()); System.out.println("使用poll()循环取出并删除元素:" + queue.poll()); String str; while ((str = queue.poll()) != null) { System.out.print(" " + str); } System.out.println(); System.out.print("使用poll()后队列的长度:" + queue.size()); }
Example 9
Source File: CloneGraph.java From LeetCode-Sol-Res with MIT License | 6 votes |
/** * BFS. O(V) Time. O(V) Space. * Use map<Integer, UndirectedGraphNode> to store cloned new graph nodes. * For each visit, connect the node with neighboring nodes. * If neighboring nodes not in new graph yet, need to create them. * Visit: * Check whether current label is in new graph: * | If not, create a new node with current label and put in map. * If neighbors exist: * | For each neighbor: * | If its not visited, add it to queue and create a new node. * | Connect current node with this neighbor. */ public UndirectedGraphNode cloneGraph2(UndirectedGraphNode node) { if (node == null) { return null; } Queue<UndirectedGraphNode> q = new ArrayDeque<>(); Map<Integer, UndirectedGraphNode> cloned = new HashMap<>(); // Cloned graph nodes. q.offer(node); cloned.put(node.label, new UndirectedGraphNode(node.label)); while (!q.isEmpty()) { UndirectedGraphNode cur = q.poll(); if (!cloned.containsKey(cur.label)) cloned.put(cur.label, new UndirectedGraphNode(cur.label)); // Put in map to set as visited. if (cur.neighbors != null) { for (UndirectedGraphNode n : cur.neighbors) { if (!cloned.containsKey(n.label)) { // Add all unvisited neighbors to the queue. q.offer(n); cloned.put(n.label, new UndirectedGraphNode(n.label)); } // Connect cloned node with every neighbor. No matter visited or not. cloned.get(cur.label).neighbors.add(cloned.get(n.label)); } } } return cloned.get(node.label); }
Example 10
Source File: RemoveInvalidParentheses.java From LeetCode-Sol-Res with MIT License | 5 votes |
/** * BFS. * Generate all possible next strings by removing one paren from current string. * First add the original string to a queue and a set to start BFS. * While queue is not empty: * | Poll a string from the queue. * | Check if the polled string is valid, if its valid: * | Set the found flag. We don't need to generate next level. * | If found is true: * | Continue to the next string in queue. * | If found is false: * | Generate all possible strings for the next level by removing one parentheses. * <p> * Note that once we found one valid string, we know the minimum number. * No need to generate the next possible strings anymore. * Use a String set to avoid BFS cycles or duplicate checks. */ public List<String> removeInvalidParentheses(String s) { if (s == null) { // "" should return [""]. return Collections.emptyList(); } List<String> res = new ArrayList<>(); Queue<String> queue = new ArrayDeque<>(); Set<String> visited = new HashSet<>(); // Store visited strings. queue.offer(s); visited.add(s); boolean found = false; // Flag to stop generating new strings. while (!queue.isEmpty()) { String cur = queue.poll(); // Visit. if (isValid(cur)) { // First valid string is found. res.add(cur); found = true; } if (found) { // No need to generate the more strings. continue; // Still check all the strings remain in queue. } // Generate all possible strings by removing one paren. for (int i = 0; i < cur.length(); i++) { if (cur.charAt(i) != '(' && cur.charAt(i) != ')') { // Skip chars that are not paren. continue; } cur = cur.substring(0, i) + cur.substring(i + 1); // Remove i. if (!visited.contains(cur)) { queue.add(cur); visited.add(cur); } } } return res; }
Example 11
Source File: TestPerformanceEvaluation.java From hbase with Apache License 2.0 | 5 votes |
@Test public void testParseOptsMultiPutsAndAutoFlushOrder() { Queue<String> opts = new LinkedList<>(); String cmdName = "sequentialWrite"; String cmdMultiPut = "--multiPut=10"; String cmdAutoFlush = "--autoFlush=true"; opts.offer(cmdAutoFlush); opts.offer(cmdMultiPut); opts.offer(cmdName); opts.offer("64"); PerformanceEvaluation.TestOptions options = null; options = PerformanceEvaluation.parseOpts(opts); assertNotNull(options); assertEquals(true, options.autoFlush); assertEquals(10, options.getMultiPut()); // Change the order of AutoFlush and Multiput opts = new LinkedList<>(); opts.offer(cmdMultiPut); opts.offer(cmdAutoFlush); opts.offer(cmdName); opts.offer("64"); options = null; options = PerformanceEvaluation.parseOpts(opts); assertNotNull(options); assertEquals(10, options.getMultiPut()); assertEquals(true, options.autoFlush); }
Example 12
Source File: AppLovinCustomEventInterstitial.java From SDK-Network-Adapters with MIT License | 5 votes |
private static void enqueueAd(final AppLovinAd ad, final String zoneId) { synchronized ( GLOBAL_INTERSTITIAL_ADS_LOCK ) { Queue<AppLovinAd> preloadedAds = GLOBAL_INTERSTITIAL_ADS.get( zoneId ); if ( preloadedAds == null ) { preloadedAds = new LinkedList<AppLovinAd>(); GLOBAL_INTERSTITIAL_ADS.put( zoneId, preloadedAds ); } preloadedAds.offer( ad ); } }
Example 13
Source File: AbstractIoSession.java From neoscada with Eclipse Public License 1.0 | 5 votes |
/** * TODO Add method documentation */ private ReadFuture newReadFuture() { Queue<ReadFuture> readyReadFutures = getReadyReadFutures(); Queue<ReadFuture> waitingReadFutures = getWaitingReadFutures(); ReadFuture future; synchronized (readyReadFutures) { future = waitingReadFutures.poll(); if (future == null) { future = new DefaultReadFuture(this); readyReadFutures.offer(future); } } return future; }
Example 14
Source File: FilmstripView.java From Camera2 with Apache License 2.0 | 5 votes |
private void recycleView(View view, int index) { Log.v(TAG, "recycleView"); final int viewType = (Integer) view.getTag(R.id.mediadata_tag_viewtype); if (viewType > 0) { Queue<View> recycledViewsForType = recycledViews.get(viewType); if (recycledViewsForType == null) { recycledViewsForType = new ArrayDeque<View>(); recycledViews.put(viewType, recycledViewsForType); } recycledViewsForType.offer(view); } }
Example 15
Source File: PolicySourceModel.java From TencentKona-8 with GNU General Public License v2.0 | 5 votes |
/** * Iterates through policy vocabulary and extracts set of namespaces used in * the policy expression. * * @return collection of used namespaces within given policy instance * @throws PolicyException Thrown if internal processing failed. */ private Collection<String> getUsedNamespaces() throws PolicyException { final Set<String> namespaces = new HashSet<String>(); namespaces.add(getNamespaceVersion().toString()); if (this.policyId != null) { namespaces.add(PolicyConstants.WSU_NAMESPACE_URI); } final Queue<ModelNode> nodesToBeProcessed = new LinkedList<ModelNode>(); nodesToBeProcessed.add(rootNode); ModelNode processedNode; while ((processedNode = nodesToBeProcessed.poll()) != null) { for (ModelNode child : processedNode.getChildren()) { if (child.hasChildren()) { if (!nodesToBeProcessed.offer(child)) { throw LOGGER.logSevereException(new PolicyException(LocalizationMessages.WSP_0081_UNABLE_TO_INSERT_CHILD(nodesToBeProcessed, child))); } } if (child.isDomainSpecific()) { final AssertionData nodeData = child.getNodeData(); namespaces.add(nodeData.getName().getNamespaceURI()); if (nodeData.isPrivateAttributeSet()) { namespaces.add(PolicyConstants.SUN_POLICY_NAMESPACE_URI); } for (Entry<QName, String> attribute : nodeData.getAttributesSet()) { namespaces.add(attribute.getKey().getNamespaceURI()); } } } } return namespaces; }
Example 16
Source File: _032_BinTree_Level_Visit_With_Line.java From algorithm-primer with MIT License | 5 votes |
public void printBinTree(TreeNode root){ if (root == null) return; Queue<TreeNode> queue = new LinkedList<>(); queue.offer(root); int nextLevel = 0; int thisLevel = 1; while (!queue.isEmpty()){ TreeNode currNode = queue.poll(); if (currNode.left != null){ queue.offer(currNode.left); nextLevel ++; } if (currNode.right != null){ queue.offer(currNode.right); nextLevel ++; } System.out.print(currNode.val + "\t"); thisLevel --; if (thisLevel == 0){ System.out.println(); thisLevel = nextLevel; nextLevel = 0; } } }
Example 17
Source File: ShortestDistanceFromExit.java From interview with Apache License 2.0 | 5 votes |
private void setDistance(Cell input[][], int x, int y, int distance[][]){ boolean visited[][] = new boolean[input.length][input[0].length]; Queue<Point> q = new LinkedList<>(); q.offer(new Point(x,y)); //Do a BFS at keep updating distance. while(!q.isEmpty()){ Point p = q.poll(); setDistanceUtil(q, input, p, getNeighbor(input, p.x+1, p.y), distance, visited); setDistanceUtil(q, input, p, getNeighbor(input, p.x, p.y+1), distance, visited); setDistanceUtil(q, input, p, getNeighbor(input, p.x-1, p.y), distance, visited); setDistanceUtil(q, input, p, getNeighbor(input, p.x, p.y-1), distance, visited); } }
Example 18
Source File: StatsFlowRuleManager.java From onos with Apache License 2.0 | 5 votes |
private void enqFlowInfo(FlowInfo flowInfo) { String key = flowInfo.uniqueFlowInfoKey(); Queue<FlowInfo> queue = flowInfoMap.get(key); if (queue == null) { Queue<FlowInfo> newQueue = new LinkedList<FlowInfo>(); newQueue.offer(flowInfo); flowInfoMap.put(key, newQueue); return; } queue.offer(flowInfo); while (queue.size() > DEFAULT_DATA_POINT_SIZE) { queue.remove(); // Removes a garbage data in the queue. } }
Example 19
Source File: WordBreakSpellChecker.java From lucene-solr with Apache License 2.0 | 4 votes |
private int generateBreakUpSuggestions(Term term, IndexReader ir, int numberBreaks, int maxSuggestions, int useMinSuggestionFrequency, SuggestWord[] prefix, Queue<SuggestWordArrayWrapper> suggestions, int totalEvaluations, BreakSuggestionSortMethod sortMethod) throws IOException { String termText = term.text(); int termLength = termText.codePointCount(0, termText.length()); int useMinBreakWordLength = minBreakWordLength; if (useMinBreakWordLength < 1) { useMinBreakWordLength = 1; } if (termLength < (useMinBreakWordLength * 2)) { return 0; } int thisTimeEvaluations = 0; for (int i = useMinBreakWordLength; i <= (termLength - useMinBreakWordLength); i++) { int end = termText.offsetByCodePoints(0, i); String leftText = termText.substring(0, end); String rightText = termText.substring(end); SuggestWord leftWord = generateSuggestWord(ir, term.field(), leftText); if (leftWord.freq >= useMinSuggestionFrequency) { SuggestWord rightWord = generateSuggestWord(ir, term.field(), rightText); if (rightWord.freq >= useMinSuggestionFrequency) { SuggestWordArrayWrapper suggestion = new SuggestWordArrayWrapper( newSuggestion(prefix, leftWord, rightWord)); suggestions.offer(suggestion); if (suggestions.size() > maxSuggestions) { suggestions.poll(); } } int newNumberBreaks = numberBreaks + 1; if (newNumberBreaks <= maxChanges) { int evaluations = generateBreakUpSuggestions(new Term(term.field(), rightWord.string), ir, newNumberBreaks, maxSuggestions, useMinSuggestionFrequency, newPrefix(prefix, leftWord), suggestions, totalEvaluations, sortMethod); totalEvaluations += evaluations; } } thisTimeEvaluations++; totalEvaluations++; if (totalEvaluations >= maxEvaluations) { break; } } return thisTimeEvaluations; }
Example 20
Source File: AlienDictionary.java From LeetCode-Sol-Res with MIT License | 4 votes |
/** * Graph. Topological Sort. BFS. * Two steps: * 1) Build a graph and in-degree from the given words. * 2) Do topological sort. * <p> * Topological sort based on Kahn's algo. * It needs a graph and each node's in-degree. * Then start with all 0 in-degree nodes, enqueue them. * While the queue is not empty, dequeue a node and add to result order. * Remove edges start from this node by reducing the in-degree of its neighbors. * If those nodes become 0 in-degree as well, enqueue. * When queue is empty, it's done. * Before return, check if the order is valid by comparing the result length with # of graph nodes. */ public String alienOrder(String[] words) { if (words == null || words.length == 0) return ""; Map<Character, Integer> inDegrees = new HashMap<>(); for (String s : words) { // Init in-degree of all characters given to 0. for (char c : s.toCharArray()) { inDegrees.put(c, 0); } } Map<Character, Set<Character>> graph = new HashMap<>(); // Use set to avoid duplicate edge. for (int i = 0; i < words.length - 1; i++) { String w1 = words[i]; String w2 = words[i + 1]; if (w1.startsWith(w2) && w1.length() > w2.length()) { // "abcee" -> "abc", invalid. return ""; } for (int j = 0; j < w1.length() && j < w2.length(); j++) { char c1 = w1.charAt(j); char c2 = w2.charAt(j); if (c1 != c2) { if (!graph.containsKey(c1)) { graph.put(c1, new HashSet<>()); } if (graph.get(c1).add(c2)) { inDegrees.put(c2, inDegrees.get(c2) + 1); } break; // Should break once one edge is found. } } } Queue<Character> queue = new ArrayDeque<>(); for (Map.Entry<Character, Integer> e : inDegrees.entrySet()) { if (e.getValue() == 0) queue.offer(e.getKey()); } StringBuilder order = new StringBuilder(); while (!queue.isEmpty()) { char n = queue.poll(); order.append(n); // Remove edges from graph by updating in degrees of neighbors. if (graph.containsKey(n)) { // Avoid NPE. for (char neighbor : graph.get(n)) { inDegrees.put(neighbor, inDegrees.get(neighbor) - 1); // Update in degree. if (inDegrees.get(neighbor) == 0) { // Add 0 in degree node to queue. queue.offer(neighbor); } } } } return order.length() == inDegrees.size() ? order.toString() : ""; // Check if all nodes are in result. }