当前位置: 首页>>代码示例>>Java>>正文


Java PriorityQueue.poll方法代码示例

本文整理汇总了Java中java.util.PriorityQueue.poll方法的典型用法代码示例。如果您正苦于以下问题:Java PriorityQueue.poll方法的具体用法?Java PriorityQueue.poll怎么用?Java PriorityQueue.poll使用的例子?那么恭喜您, 这里精选的方法代码示例或许可以为您提供帮助。您也可以进一步了解该方法所在java.util.PriorityQueue的用法示例。


在下文中一共展示了PriorityQueue.poll方法的15个代码示例,这些例子默认根据受欢迎程度排序。您可以为喜欢或者感觉有用的代码点赞,您的评价将有助于系统推荐出更棒的Java代码示例。

示例1: obtainFirst

import java.util.PriorityQueue; //导入方法依赖的package包/类
private static synchronized Item obtainFirst() throws InterruptedException {
    if (TICK == null) {
        return null;
    }
    PriorityQueue<Item> q = TICK.queue;
    Item first = q.poll();
    if (first == null) {
        TICK = null;
        return null;
    }
    long delay = first.when - System.currentTimeMillis();
    if (delay > 0) {
        q.add(first);
        TickTac.class.wait(delay);
        return null;
    }
    return first;
}
 
开发者ID:apache,项目名称:incubator-netbeans,代码行数:19,代码来源:RequestProcessor.java

示例2: insertMoves

import java.util.PriorityQueue; //导入方法依赖的package包/类
private void insertMoves() {
  SpillMoveSet spillMoves =
      new SpillMoveSet(this, code, numberOfArgumentRegisters + NUMBER_OF_SENTINEL_REGISTERS);
  for (LiveIntervals intervals : liveIntervals) {
    if (intervals.hasSplits()) {
      LiveIntervals current = intervals;
      PriorityQueue<LiveIntervals> sortedChildren =
          new PriorityQueue<>((o1, o2) -> Integer.compare(o1.getStart(), o2.getStart()));
      sortedChildren.addAll(current.getSplitChildren());
      for (LiveIntervals split = sortedChildren.poll();
          split != null;
          split = sortedChildren.poll()) {
        int position = split.getStart();
        spillMoves.addSpillOrRestoreMove(toGapPosition(position), split, current);
        current = split;
      }
    }
  }

  resolveControlFlow(spillMoves);
  firstParallelMoveTemporary = maxRegisterNumber + 1;
  maxRegisterNumber += spillMoves.scheduleAndInsertMoves(maxRegisterNumber + 1);
}
 
开发者ID:inferjay,项目名称:r8,代码行数:24,代码来源:LinearScanRegisterAllocator.java

示例3: shortest

import java.util.PriorityQueue; //导入方法依赖的package包/类
protected void shortest()
{
    IVertex s = _startVertex;
    IVertex u;

    INITIALIZE_SINGLE_SOURCE(s);

    HashSet<IVertex> S = new HashSet<>();

    PriorityQueue<IVertex> Q = new PriorityQueue<>(_graph_input.vertices().size(), this.new keyComparator());
    Q.addAll(_graph_input.vertices());

    while (!Q.isEmpty()) {
        u = Q.poll();
        S.add(u);

        for (IVertex v : _graph_input.getNeighborsOf(u)) {
            RELAX(u, v);
        }
    }

    // create the tree

    _result_algorithm = new ShortestPathsTree(_PIE, _startVertex, _DISTANCE);
    _result_algorithm.setTag(getTag() + " result");
}
 
开发者ID:Erdos-Graph-Framework,项目名称:Erdos,代码行数:27,代码来源:DijkstraShortestPath.java

示例4: split

import java.util.PriorityQueue; //导入方法依赖的package包/类
public static List<Geometry> split(Geometry given, double maxArea, Predicate<Geometry> predicate) {
    List<Geometry> others = newArrayList();
    PriorityQueue<Geometry> queue = new PriorityQueue<>(comparing(Geometry::getArea).reversed());
    queue.add(given);

    while (queue.peek().getEnvelope().getArea() > maxArea) {
        Geometry current = queue.poll();
        Point centroid = current.getCentroid();
        Geometry bbox = current.getEnvelope();
        checkState(bbox.getCoordinates().length == 5);
        for (int i = 0; i < 4; i++) {
            Geometry intersection = current.intersection(box(centroid, bbox.getCoordinates()[i]));
            if (!intersection.isEmpty()) {
                if (predicate.test(intersection)) {
                    others.add(intersection);
                }
                else {
                    queue.add(intersection);
                }
            }
        }
    }

    return ImmutableList.<Geometry> builder().addAll(newArrayList(queue)).addAll(others).build();
}
 
开发者ID:Mappy,项目名称:fpm,代码行数:26,代码来源:LargePolygonSplitter.java

示例5: GetAbundanceByMS1_TopN

import java.util.PriorityQueue; //导入方法依赖的package包/类
public float GetAbundanceByMS1_TopN(int topN, float pepweight) {
    if (PeptideID.isEmpty()) {
        return 0;
    }
    PriorityQueue<Float> TopQueue = new PriorityQueue<>(PeptideID.size(), Collections.reverseOrder());
    for (PepIonID peptide : PeptideID.values()) {
        if (peptide.PeakHeight != null && peptide.FilteringWeight > pepweight) {
            TopQueue.add(peptide.PeakHeight[0]);
        }
    }

    float totalabundance = 0f;
    int num = Math.min(topN, TopQueue.size());

    for (int i = 0; i < num; i++) {
        totalabundance += TopQueue.poll();
    }
    return totalabundance / num;
}
 
开发者ID:YcheCourseProject,项目名称:DIA-Umpire-Maven,代码行数:20,代码来源:ProtID.java

示例6: getAlternativeBroker

import java.util.PriorityQueue; //导入方法依赖的package包/类
public KafkaBroker getAlternativeBroker(TopicPartition topicPartition,
                                        double tpBytesIn, double tpBytesOut) {
  PriorityQueue<KafkaBroker> brokerQueue =
      new PriorityQueue<>(new KafkaBroker.KafkaBrokerComparator());

  for (Map.Entry<Integer, KafkaBroker> entry : brokers.entrySet()) {
    KafkaBroker broker = entry.getValue();
    if (!broker.hasTopicPartition(topicPartition)) {
      brokerQueue.add(broker);
    }
  }
  // we will get the broker with the least network usage
  KafkaBroker leastUsedBroker = brokerQueue.poll();
  LOG.info("LeastUsedBroker for replacing {} : {}", topicPartition, leastUsedBroker.id());
  boolean success = leastUsedBroker.reserveInBoundBandwidth(topicPartition, tpBytesIn);
  success &= leastUsedBroker.reserveOutBoundBandwidth(topicPartition, tpBytesOut);

  if (!success) {
    LOG.error("Failed to allocate resource to replace {}", topicPartition);
    return null;
  } else {
    return leastUsedBroker;
  }
}
 
开发者ID:pinterest,项目名称:doctorkafka,代码行数:25,代码来源:KafkaCluster.java

示例7: onEventTime

import java.util.PriorityQueue; //导入方法依赖的package包/类
/**
 * Occurs when an event-time timer fires due to watermark progression.
 *
 * @param timer the timer details.
 */
@Override
public void onEventTime(InternalTimer<K, VoidNamespace> timer) throws Exception {

    long currentWatermark = internalTimerService.currentWatermark();

    PriorityQueue<Long> sortedTimestamps = getSortedTimestamps();
    while (!sortedTimestamps.isEmpty() && sortedTimestamps.peek() <= currentWatermark) {
        long timestamp = sortedTimestamps.poll();
        for (T event : elementQueueState.get(timestamp)) {
            output.collect(new StreamRecord<>(event, timestamp));
        }
        elementQueueState.remove(timestamp);
    }

    if (sortedTimestamps.isEmpty()) {
        elementQueueState.clear();
    }

    if (!sortedTimestamps.isEmpty()) {
        saveRegisterWatermarkTimer();
    }
}
 
开发者ID:pravega,项目名称:flink-connectors,代码行数:28,代码来源:EventTimeOrderingOperator.java

示例8: spreadLightingDijkstra

import java.util.PriorityQueue; //导入方法依赖的package包/类
void spreadLightingDijkstra(List<LightingPoint> sources) {
	if (sources.isEmpty())
		return;
	HashSet<LightingPoint> out = new HashSet<>();
	PriorityQueue<LightingPoint> in = new PriorityQueue<>(sources.size(),
               new LightingPoint.LightValueComparator());
	// consider that the input sources are done (this is not a good assumption if different
	// light sources have different values......)
	out.addAll(sources);
	
	in.addAll(sources);
	while (!in.isEmpty()) {
		LightingPoint current = in.poll();
		out.add(current);
		
		if (current.lightValue <= lightValues[current.x][current.y] || current.lightValue < 0) {
			continue;
		}
		lightValues[current.x][current.y] = current.lightValue;
		lightFlow[current.x][current.y] = current.flow;
		if (lightFlow[current.x][current.y] == Direction.SOURCE
				&& current.flow != Direction.SOURCE) {
			System.out.println("There's a bug in the source map!");
		}
		List<LightingPoint> neighbors = getNeighbors(current);
		for (LightingPoint next : neighbors) {
			if (out.contains(next)) {
				continue;
			}
			in.add(next);
		}
	}
}
 
开发者ID:DreamBlocks,项目名称:DreamBlocks,代码行数:34,代码来源:LightingEngine.java

示例9: shortestPath

import java.util.PriorityQueue; //导入方法依赖的package包/类
public void shortestPath(int source, int destination) {
    Set<Node> visited = new HashSet<>();
    PriorityQueue<Node> pQueue = new PriorityQueue<>(new Comparator<Node>() {
        @Override
        public int compare(Node o1, Node o2) {
            return o1.cost - o2.cost;
        }
    });
    nodes[source].cost = 0;
    pQueue.add(nodes[source]);
    while(!pQueue.isEmpty()) {
        Node currVertex = pQueue.poll();
        for(int i = 0; i < graph.length; i++) {
            if(graph[currVertex.id][i]!=0 && !visited.contains(nodes[i]) ) {
                if(!pQueue.contains(nodes[i])) {
                    nodes[i].cost = currVertex.cost + graph[currVertex.id][i];
                    nodes[i].parent = currVertex;
                    pQueue.add(nodes[i]);
                }
                else {
                    nodes[i].cost = Math.min(nodes[i].cost, currVertex.cost + graph[currVertex.id][i]);
                    if(nodes[i].cost == currVertex.cost + graph[currVertex.id][i])
                        nodes[i].parent = currVertex;
                }
            }
        }
        visited.add(currVertex);
    }
}
 
开发者ID:iiitv,项目名称:algos,代码行数:30,代码来源:Dijkstra.java

示例10: solve

import java.util.PriorityQueue; //导入方法依赖的package包/类
public static boolean solve(Cell start, Cell goal, Heuristic heuristic, CellComparator comp ){
    if (heuristic == null || comp == null | goal == null || start == null) return false;
    Astar.goal = goal;
    HashSet<Integer> visited = new HashSet<>();
    PriorityQueue<Cell> frontier = new PriorityQueue<>(comp);
    visited.add(start.id());
    frontier.add(start);
    start.setAsStartNode();
    Cell curr;
    while( (curr = frontier.poll()) != null ){
        // Handles edges
        if( curr.isEdge() ){
            if(visited.contains(curr.firstedge().id()))
                continue;
            curr.firstedge().movedFrom(curr, curr.heuristicCost());
            curr = curr.firstedge();
            visited.add(curr.id());
            if( curr.id() == goal.id() )
                return true;
        }
        // Adds new states
        for( Cell next : curr.edges() )
            if( !visited.contains(next.id()) ){
                next.movedFrom(curr, heuristic.calc(next, goal));
                visited.add(next.id());
                frontier.add(next);
            }
    }
    return false;
}
 
开发者ID:Baizey,项目名称:Helpers,代码行数:31,代码来源:Astar.java

示例11: main

import java.util.PriorityQueue; //导入方法依赖的package包/类
@SuppressWarnings("Duplicates")
public static void main(String[] args) {
    Scanner scanner = new Scanner(System.in);

    PriorityQueue<Integer> minHeap = new PriorityQueue<>(10, Collections.reverseOrder());
    PriorityQueue<Integer> maxHeap = new PriorityQueue<>(10);

    int n = scanner.nextInt();

    for (int i = 0; i < n; i++) {
        int num = scanner.nextInt();

        if (minHeap.size() <= maxHeap.size()) {
            minHeap.add(num);
        } else {
            maxHeap.add(num);
        }

        while (!minHeap.isEmpty() && !maxHeap.isEmpty() && minHeap.peek() > maxHeap.peek()) {
            int min = minHeap.poll();
            int max = maxHeap.poll();

            minHeap.add(max);
            maxHeap.add(min);
        }

        double median = (minHeap.size() == maxHeap.size() ? ((minHeap.peek() + maxHeap.peek()) / 2.0) : minHeap.peek());

        System.out.println(median);
    }
}
 
开发者ID:viatsko,项目名称:hack,代码行数:32,代码来源:HeapsFindTheRunningMedian.java

示例12: assignLeftOvers

import java.util.PriorityQueue; //导入方法依赖的package包/类
/**
 * assign the remaining work units to hosts/fragments based on least load
 * @param leftOvers
 */
private void assignLeftOvers(List<WorkWrapper> leftOvers) {
  PriorityQueue<FragmentWork> queue = new PriorityQueue<>();
  List<FragmentWork> fragments = getFragments();
  queue.addAll(fragments);

  for (WorkWrapper work : leftOvers) {
    FragmentWork fragment = queue.poll();
    fragment.addWork(work);
    queue.add(fragment);
  }
}
 
开发者ID:dremio,项目名称:dremio-oss,代码行数:16,代码来源:AssignmentCreator2.java

示例13: main

import java.util.PriorityQueue; //导入方法依赖的package包/类
public static void main(String[] args) {
    Scanner scan = new Scanner(System.in);
    int n = scan.nextInt();
    
    /* Create PriorityQueue and add/remove entries */
    PriorityQueue<Student> pq = new PriorityQueue<>(n, new StudentComparator());
    while (n-- > 0) {
        String event = scan.next();
        switch (event) {
            case "ENTER":
                String fname = scan.next();
                double cgpa  = scan.nextDouble();
                int    token = scan.nextInt();
                pq.add(new Student(fname, cgpa, token));
                break;
            case "SERVED":
                pq.poll();
                break;
            default:
                break;
        } 
    }
    scan.close();
    
    /* Print Student names */
    if (pq.isEmpty()) {
        System.out.println("EMPTY");
    } else {
        while (!pq.isEmpty()) {
            Student s = pq.remove();
            System.out.println(s.getFname());
        }
    }
}
 
开发者ID:hell-sing,项目名称:hacker-rank,代码行数:35,代码来源:PriorityQueue.java

示例14: dijkstra

import java.util.PriorityQueue; //导入方法依赖的package包/类
protected BroadcastTree dijkstra(Map<DatapathId, Set<Link>> links, DatapathId root,
           Map<Link, Integer> linkCost,
           boolean isDstRooted) {
   	HashMap<DatapathId, Link> nexthoplinks = new HashMap<DatapathId, Link>();
   	HashMap<DatapathId, Integer> cost = new HashMap<DatapathId, Integer>();
   	int w;
   	
   	for (DatapathId node : links.keySet()) {
   		nexthoplinks.put(node, null);
   		cost.put(node, MAX_PATH_WEIGHT);
   	}
	
   	HashMap<DatapathId, Boolean> seen = new HashMap<DatapathId, Boolean>();
   	PriorityQueue<NodeDist> nodeq = new PriorityQueue<NodeDist>();
   	nodeq.add(new NodeDist(root, 0));
   	cost.put(root, 0);
   	
   	while (nodeq.peek() != null) {
   		NodeDist n = nodeq.poll();
   		DatapathId cnode = n.getNode();
   		int cdist = n.getDist();
   		
   		if (cdist >= MAX_PATH_WEIGHT) break;
   		if (seen.containsKey(cnode)) continue;
   		seen.put(cnode, true);

   		for (Link link : links.get(cnode)) {
   			DatapathId neighbor;

   			if (isDstRooted == true) {
   				neighbor = link.getSrc();
   			} else {
   				neighbor = link.getDst();
   			}
       
   			// links directed toward cnode will result in this condition
   			if (neighbor.equals(cnode)) continue;

   			if (seen.containsKey(neighbor)) continue;

   			if (linkCost == null || linkCost.get(link) == null) {
   				w = 1;
   			} else {
   				w = linkCost.get(link);
   			}
   			
   			int ndist = cdist + w; // the weight of the link, always 1 in current version of floodlight.
   			if (ndist < cost.get(neighbor)) {
   				cost.put(neighbor, ndist);
   				nexthoplinks.put(neighbor, link);
   				
   				NodeDist ndTemp = new NodeDist(neighbor, ndist);
   				// Remove an object that's already in there.
   				// Note that the comparison is based on only the node id,
   				// and not node id and distance.
   				nodeq.remove(ndTemp);
   				// add the current object to the queue.
   				nodeq.add(ndTemp);
   			}
   		}
   	}

   	BroadcastTree ret = new BroadcastTree(nexthoplinks, cost);

	return ret;
}
 
开发者ID:xuraylei,项目名称:fresco_floodlight,代码行数:67,代码来源:TopologyInstance.java

示例15: flatten

import java.util.PriorityQueue; //导入方法依赖的package包/类
public ClusterModel flatten(HierarchicalClusterModel model, ExampleSet exampleSet) throws OperatorException {
	HierarchicalClusterNode root = model.getRootNode();
	int numberOfClusters = getParameterAsInt(PARAMETER_NUMBER_OF_CLUSTER);

	// creating priorityQueue using reversing comparator
	PriorityQueue<HierarchicalClusterNode> queue = new PriorityQueue<HierarchicalClusterNode>(numberOfClusters,
			new Comparator<HierarchicalClusterNode>() {

		@Override
		public int compare(HierarchicalClusterNode o1, HierarchicalClusterNode o2) {
			int value = -1 * Double.compare(o1.getDistance(), o2.getDistance());
			if (value != 0) {
				return value;
			} else {
				return -1 * Double.compare(o1.getNumberOfExamplesInSubtree(), o2.getNumberOfExamplesInSubtree());
			}
		}
	});

	// Iteratively descend within graph by splitting at greatest node until queue is full or
	// enough leafs are collected
	LinkedList<HierarchicalClusterNode> leafs = new LinkedList<HierarchicalClusterNode>();
	queue.add(root);
	while (queue.size() < numberOfClusters - leafs.size()) {
		HierarchicalClusterNode topNode = queue.poll();
		if (topNode.getSubNodes().size() > 0) {
			queue.addAll(topNode.getSubNodes());
		} else {
			leafs.add(topNode);
		}
	}
	queue.addAll(leafs);

	// construct flat cluster model from nodes
	ClusterModel flatModel = new ClusterModel(exampleSet, numberOfClusters,
			getParameterAsBoolean(PARAMETER_ADD_AS_LABEL), getParameterAsBoolean(PARAMETER_REMOVE_UNLABELED));
	int i = 0;
	for (HierarchicalClusterNode node : queue) {
		Cluster flatCluster = flatModel.getCluster(i);
		for (Object exampleId : node.getExampleIdsInSubtree()) {
			flatCluster.assignExample(exampleId);
		}
		i++;
	}

	// delivering adapted example set
	if (exampleSetOutput.isConnected()) {
		exampleSetOutput.deliver(flatModel.apply((ExampleSet) exampleSet.clone()));
	}
	return flatModel;
}
 
开发者ID:transwarpio,项目名称:rapidminer,代码行数:52,代码来源:FlattenClusterModel.java


注:本文中的java.util.PriorityQueue.poll方法示例由纯净天空整理自Github/MSDocs等开源代码及文档管理平台,相关代码片段筛选自各路编程大神贡献的开源项目,源码版权归原作者所有,传播和使用请参考对应项目的License;未经允许,请勿转载。