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


Java PriorityQueue.add方法代码示例

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


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

示例1: processElement

import java.util.PriorityQueue; //导入方法依赖的package包/类
@Override
public void processElement(AisMessage message, Context context, Collector<AisMessage> out)
    throws Exception {

  TimerService timerService = context.timerService();

  PriorityQueue<AisMessage> queue = queueState.value();
  if (queue == null) {
    queue =
        new PriorityQueue<>(MAX_NUMBER_OF_QUEUED_ELEMENTS + 1, new PositionMessagesComparator());
  }
  long timestamp = System.currentTimeMillis();
  if (context.timestamp() > timerService.currentWatermark()) {
    queue.add(message);
    queueState.update(queue);
    // register a timer to be fired when the watermark passes this message timestamp
    timerService.registerEventTimeTimer(timestamp);
  } else {
    // logger.info("out of order message: " + message.toString());
    // throw new Exception(timerService.currentWatermark() + "out of order message: "
    // + message.toString());
    queue.add(message);
    queueState.update(queue);

  }
}
 
开发者ID:ehabqadah,项目名称:in-situ-processing-datAcron,代码行数:27,代码来源:AisMessagesStreamSorter.java

示例2: CalculateBaseLine

import java.util.PriorityQueue; //导入方法依赖的package包/类
private void CalculateBaseLine() {
    _baseLine = 0f;
    PriorityQueue<Float> IntensityQueue = new PriorityQueue<>();
    for (XYData point : SmoothData.Data) {
        IntensityQueue.add(point.getY());
    }

    if (IntensityQueue.size() > 10) {
        for (int i = 0; i < IntensityQueue.size() / 10; i++) {
            _baseLine += IntensityQueue.poll();
        }
        _baseLine /= (IntensityQueue.size() / 10);
    } else {
        _baseLine = IntensityQueue.poll();
    }
}
 
开发者ID:YcheCourseProject,项目名称:DIA-Umpire-Maven,代码行数:17,代码来源:PeakCurve.java

示例3: mergeSorted

import java.util.PriorityQueue; //导入方法依赖的package包/类
public static List<Integer> mergeSorted(List<List<Integer>> sortedArrays) {
    List<Iterator<Integer>> iters = new ArrayList<>(sortedArrays.size());
    for (List<Integer> array : sortedArrays)
        iters.add(array.iterator());

    PriorityQueue<ArrayEntry> minHeap = new PriorityQueue<>(iters.size(), ArrayEntry::compareTo);

    for (int i  = 0; i < iters.size(); i++) {
        if (iters.get(i).hasNext())
            minHeap.add(new ArrayEntry(iters.get(i).next(),i));
    }
    List<Integer> result = new ArrayList<>();
    while (!minHeap.isEmpty()) {
        ArrayEntry temp = minHeap.poll();
        result.add(temp.value);
        if (iters.get(temp.arrayId).hasNext())
            minHeap.add(new ArrayEntry(iters.get(temp.arrayId).next(),temp.arrayId));
    }
    return result;
}
 
开发者ID:gardncl,项目名称:elements-of-programming-interviews-solutions,代码行数:21,代码来源:MergeSortedFiles.java

示例4: peekAllCustomerByOffice

import java.util.PriorityQueue; //导入方法依赖的package包/类
public PriorityQueue<QCustomer> peekAllCustomerByOffice(QOffice office) {

        //  Debug.
        QLog.l().logQUser().debug("==> Start: peekAllCustomerByOffice: " + office);

        //  CM:  Init vars of all customers wanting this service, and those in input office.
        PriorityQueue<QCustomer> customers = getCustomers();
        PriorityQueue<QCustomer> custHere = new PriorityQueue<QCustomer>();
        QCustomer customer = null;

        //  CM:  Loop through all customers to see if they are in the office input.   
        for (Iterator<QCustomer> itr = customers.iterator(); itr.hasNext();) {
            final QCustomer cust = itr.next();
            //QLog.l().logQUser().debug("Polling customer: " + cust);
            //QLog.l().logQUser().debug("  Office: " + cust.getOffice());
            //QLog.l().logQUser().debug(" Service: " + cust.getService().name);
            if (cust.getOffice().equals(office)) {
                custHere.add(cust);
            }
        }

        //  Debug.
        QLog.l().logQUser().debug("==> End: peekAllCustomerByOffice: " + office + "; Customers: " + custHere.size());

        return custHere;
    }
 
开发者ID:bcgov,项目名称:sbc-qsystem,代码行数:27,代码来源:QService.java

示例5: getBestResults

import java.util.PriorityQueue; //导入方法依赖的package包/类
public static String[] getBestResults(float[] confidenceLevels, String[] labels) {
    // Find the best classifications.
    PriorityQueue<Pair<String, Float>> pq = new PriorityQueue<>(3,
            new Comparator<Pair<String, Float>>() {
                @Override
                public int compare(Pair<String, Float> lhs, Pair<String, Float> rhs) {
                    // Intentionally reversed to put high confidence at the head of the queue.
                    return Float.compare(rhs.second, lhs.second);
                }
            });
    for (int i = 0; i < confidenceLevels.length; ++i) {
        if (confidenceLevels[i] > RESULT_CONFIDENCE_THRESHOLD) {
            pq.add(Pair.create(labels[i], confidenceLevels[i]));
        }
    }

    int recognitionsSize = Math.min(pq.size(), MAX_BEST_RESULTS);
    String[] recognitions = new String[recognitionsSize];
    for (int i = 0; i < recognitionsSize; ++i) {
        recognitions[i] = pq.poll().first;
    }
    return recognitions;
}
 
开发者ID:googlecodelabs,项目名称:androidthings-imageclassifier,代码行数:24,代码来源:Helper.java

示例6: 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:rshaghoulian,项目名称:HackerRank_solutions,代码行数:35,代码来源:Solution.java

示例7: 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

示例8: getShortestPathsIntern

import java.util.PriorityQueue; //导入方法依赖的package包/类
@Override
protected List<List<E>> getShortestPathsIntern(V source, V target, int k) {
	PriorityQueue<WeightedPath> prioQ = new PriorityQueue<WeightedPath>();
	List<List<E>> found_paths = new LinkedList<List<E>>();

	Transformer<E, Double> delta = prepareTransformations(target);

	// Initialize with start vertex.
	prioQ.add(new WeightedPath(source));

	while (!prioQ.isEmpty() && found_paths.size() < k) {
		WeightedPath curPath = prioQ.poll(); // get & remove next shortest
		V curV = curPath.getLast();

		if (curV.equals(target)) {
			found_paths.add(curPath.getPath());
			continue;
		}

		// Create new paths for every expanded vertex ...
		for (V nextV : graph.getSuccessors(curV)) {
			if (curPath.contains(nextV))
				continue; // Prevent looping!

			// ... and every possible edge.
			for (E e : graph.findEdgeSet(curV, nextV)) {
				if (Double.isInfinite(delta.transform(e)))
					continue; // Skip unreachable vertices.

				WeightedPath tmpPath = new WeightedPath(curPath); // clone
				tmpPath.addHop(e, delta.transform(e), nextV);

				prioQ.add(tmpPath);
			}
		}
	}

	return found_paths;
}
 
开发者ID:KeepTheBeats,项目名称:alevin-svn2,代码行数:40,代码来源:Eppstein.java

示例9: 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

示例10: selectInputStreams

import java.util.PriorityQueue; //导入方法依赖的package包/类
@Override
public void selectInputStreams(Collection<EditLogInputStream> streams,
    long fromTxnId, boolean inProgressOk) throws IOException {

  QuorumCall<AsyncLogger, RemoteEditLogManifest> q =
      loggers.getEditLogManifest(fromTxnId, inProgressOk);
  Map<AsyncLogger, RemoteEditLogManifest> resps =
      loggers.waitForWriteQuorum(q, selectInputStreamsTimeoutMs,
          "selectInputStreams");
  
  LOG.debug("selectInputStream manifests:\n" +
      Joiner.on("\n").withKeyValueSeparator(": ").join(resps));
  
  final PriorityQueue<EditLogInputStream> allStreams = 
      new PriorityQueue<EditLogInputStream>(64,
          JournalSet.EDIT_LOG_INPUT_STREAM_COMPARATOR);
  for (Map.Entry<AsyncLogger, RemoteEditLogManifest> e : resps.entrySet()) {
    AsyncLogger logger = e.getKey();
    RemoteEditLogManifest manifest = e.getValue();
    
    for (RemoteEditLog remoteLog : manifest.getLogs()) {
      URL url = logger.buildURLToFetchLogs(remoteLog.getStartTxId());

      EditLogInputStream elis = EditLogFileInputStream.fromUrl(
          connectionFactory, url, remoteLog.getStartTxId(),
          remoteLog.getEndTxId(), remoteLog.isInProgress());
      allStreams.add(elis);
    }
  }
  JournalSet.chainAndMakeRedundantStreams(streams, allStreams, fromTxnId);
}
 
开发者ID:naver,项目名称:hadoop,代码行数:32,代码来源:QuorumJournalManager.java

示例11: getObject

import java.util.PriorityQueue; //导入方法依赖的package包/类
public Queue<Object> getObject(final String command) throws Exception {
	Object templates = Gadgets.createTemplatesImpl(command);

	ConstantTransformer constant = new ConstantTransformer(String.class);

	// mock method name until armed
	Class[] paramTypes = new Class[] { String.class };
	Object[] args = new Object[] { "foo" };
	InstantiateTransformer instantiate = new InstantiateTransformer(
			paramTypes, args);

	// grab defensively copied arrays
	paramTypes = (Class[]) Reflections.getFieldValue(instantiate, "iParamTypes");
	args = (Object[]) Reflections.getFieldValue(instantiate, "iArgs");

	ChainedTransformer chain = new ChainedTransformer(new Transformer[] { constant, instantiate });

	// create queue with numbers
	PriorityQueue<Object> queue = new PriorityQueue<Object>(2, new TransformingComparator(chain));
	queue.add(1);
	queue.add(1);

	// swap in values to arm
	Reflections.setFieldValue(constant, "iConstant", TrAXFilter.class);
	paramTypes[0] = Templates.class;
	args[0] = templates;

	return queue;
}
 
开发者ID:RickGray,项目名称:ysoserial-plus,代码行数:30,代码来源:CommonsCollections4.java

示例12: initializeWorklist

import java.util.PriorityQueue; //导入方法依赖的package包/类
/**
 * Initializes the priority queue used for the work list of blocks and adds the start block.
 */
private static <T extends AbstractBlockBase<T>> PriorityQueue<T> initializeWorklist(T startBlock, BitSet visitedBlocks) {
    PriorityQueue<T> result = new PriorityQueue<>(INITIAL_WORKLIST_CAPACITY, new BlockOrderComparator<>());
    result.add(startBlock);
    visitedBlocks.set(startBlock.getId());
    return result;
}
 
开发者ID:AdoptOpenJDK,项目名称:openjdk-jdk10,代码行数:10,代码来源:ComputeBlockOrder.java

示例13: clusterDijkstra

import java.util.PriorityQueue; //导入方法依赖的package包/类
protected BroadcastTree clusterDijkstra(Cluster c, 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 : c.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 : c.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,代码行数:69,代码来源:TopologyInstance.java

示例14: recognizeImage

import java.util.PriorityQueue; //导入方法依赖的package包/类
@Override
public List<Recognition> recognizeImage(final Bitmap bitmap) {
  // Log this method so that it can be analyzed with systrace.
  Trace.beginSection("recognizeImage");

  Trace.beginSection("preprocessBitmap");
  // Preprocess the image data from 0-255 int to normalized float based
  // on the provided parameters.
  bitmap.getPixels(intValues, 0, bitmap.getWidth(), 0, 0, bitmap.getWidth(), bitmap.getHeight());
  for (int i = 0; i < intValues.length; ++i) {
    final int val = intValues[i];
    floatValues[i * 3 + 0] = (((val >> 16) & 0xFF) - imageMean) / imageStd;
    floatValues[i * 3 + 1] = (((val >> 8) & 0xFF) - imageMean) / imageStd;
    floatValues[i * 3 + 2] = ((val & 0xFF) - imageMean) / imageStd;
  }
  Trace.endSection();

  // Copy the input data into TensorFlow.
  Trace.beginSection("fillNodeFloat");
  inferenceInterface.fillNodeFloat(
      inputName, new int[] {1, inputSize, inputSize, 3}, floatValues);
  Trace.endSection();

  // Run the inference call.
  Trace.beginSection("runInference");
  inferenceInterface.runInference(outputNames);
  Trace.endSection();

  // Copy the output Tensor back into the output array.
  Trace.beginSection("readNodeFloat");
  inferenceInterface.readNodeFloat(outputName, outputs);
  Trace.endSection();

  // Find the best classifications.
  PriorityQueue<Recognition> pq =
      new PriorityQueue<Recognition>(
          3,
          new Comparator<Recognition>() {
            @Override
            public int compare(Recognition lhs, Recognition rhs) {
              // Intentionally reversed to put high confidence at the head of the queue.
              return Float.compare(rhs.getConfidence(), lhs.getConfidence());
            }
          });
  for (int i = 0; i < outputs.length; ++i) {
    if (outputs[i] > THRESHOLD) {
      pq.add(
          new Recognition(
              "" + i, labels.size() > i ? labels.get(i) : "unknown", outputs[i], null));
    }
  }
  final ArrayList<Recognition> recognitions = new ArrayList<Recognition>();
  int recognitionsSize = Math.min(pq.size(), MAX_RESULTS);
  for (int i = 0; i < recognitionsSize; ++i) {
    recognitions.add(pq.poll());
  }
  Trace.endSection(); // "recognizeImage"
  return recognitions;
}
 
开发者ID:jxtz518,项目名称:Tensorflow_Andriod_With_Audio_Output,代码行数:60,代码来源:TensorFlowImageClassifier.java

示例15: getK

import java.util.PriorityQueue; //导入方法依赖的package包/类
public static ValueIndexPair[] getK(final ValueIndexPair[] array,
        final int k, final Comparator<ValueIndexPair> comparator) {
    if (k < 1) {
        throw new IllegalArgumentException("k must be greater than zero!");
    }
    if (k > array.length) {
        throw new IllegalArgumentException(
                "k must be smaller or equal to the length of the array!");
    }

    // heapComp induces the opposite ordering to comparator
    final Comparator<ValueIndexPair> heapComp =
            new Comparator<ValueIndexPair>() {
                @Override
                public int compare(final ValueIndexPair o1,
                        final ValueIndexPair o2) {
                    return -comparator.compare(o1, o2);
                }
            };

    // heap structure to keep first k elements
    final PriorityQueue<ValueIndexPair> heap =
            new PriorityQueue<ValueIndexPair>(k, heapComp);

    for (int i = 0; i < array.length; i++) {
        // fill heap
        if (i < k) {
            heap.add(array[i]);
        } else {
            // check if head of heap is larger than new element
            if (comparator.compare(array[i], heap.peek()) == -1) {
                // remove head
                heap.poll();
                // add new element and restore heap structure
                heap.add(array[i]);
            }
        }

    }

    return heap.toArray(new ValueIndexPair[heap.size()]);

}
 
开发者ID:knime,项目名称:knime-activelearning,代码行数:44,代码来源:ValueIndexPair.java


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