Example usage for java.util PriorityQueue iterator

List of usage examples for java.util PriorityQueue iterator

Introduction

In this page you can find the example usage for java.util PriorityQueue iterator.

Prototype

public Iterator<E> iterator() 

Source Link

Document

Returns an iterator over the elements in this queue.

Usage

From source file:Main.java

public static void main(String args[]) {

    PriorityQueue<Integer> prq = new PriorityQueue<Integer>();

    for (int i = 0; i < 10; i++) {
        prq.add(i);//from   w  w  w .  j  a v  a 2  s  .  co  m
    }

    // create iterator from the queue
    Iterator it = prq.iterator();

    while (it.hasNext()) {
        System.out.println("Value: " + it.next());
    }
}

From source file:main.java.RMDupper.java

public static void checkForDuplication(DupStats dupStats, OccurenceCounterMerged occurenceCounterMerged,
        SAMFileWriter outputSam, Boolean allReadsAsMerged,
        PriorityQueue<ImmutableTriple<Integer, Integer, SAMRecord>> recordBuffer,
        PriorityQueue<ImmutableTriple<Integer, Integer, SAMRecord>> duplicateBuffer, Set<String> discardSet) {
    // At this point recordBuffer contains all alignments that overlap with its first entry
    // Therefore the task here is to de-duplicate for the first entry in recordBuffer
    duplicateBuffer.clear();//from w w w .ja v  a 2 s . com

    Iterator<ImmutableTriple<Integer, Integer, SAMRecord>> it = recordBuffer.iterator();
    while (it.hasNext()) {
        ImmutableTriple<Integer, Integer, SAMRecord> maybeDuplicate = it.next();

        if (allReadsAsMerged) {
            if (recordBuffer.peek().left.equals(maybeDuplicate.left)
                    && recordBuffer.peek().middle.equals(maybeDuplicate.middle)) {
                duplicateBuffer.add(maybeDuplicate);
            }
        } else {
            // We build a logic table
            EnumSet<DL> testConditon = EnumSet.noneOf(DL.class);
            if (recordBuffer.peek().right.getReadName().startsWith("M_")) {
                testConditon.add(DL.buffer_read_merged);
            } else if (recordBuffer.peek().right.getReadName().startsWith("F_")) {
                testConditon.add(DL.buffer_read_one);
            } else if (recordBuffer.peek().right.getReadName().startsWith("R_")) {
                testConditon.add(DL.buffer_read_two);
            } else {
                throw new RuntimeException("Unlabelled read '" + recordBuffer.peek().right.getReadName()
                        + "' read name must start with one of M_,F_,R when not treating all reads as merged");
            }

            if (maybeDuplicate.right.getReadName().startsWith("M_")) {
                testConditon.add(DL.maybed_read_merged);
            } else if (maybeDuplicate.right.getReadName().startsWith("F_")) {
                testConditon.add(DL.maybed_read_one);
            } else if (maybeDuplicate.right.getReadName().startsWith("R_")) {
                testConditon.add(DL.maybed_read_two);
            } else {
                System.err.println("Unlabelled read '" + maybeDuplicate.right.getReadName()
                        + "' read name must start with one of M_,F_,R when not treating all reads as merged");
            }

            if (recordBuffer.peek().left.equals(maybeDuplicate.left)) {
                testConditon.add(DL.equal_alignment_start);
            }
            if (recordBuffer.peek().middle.equals(maybeDuplicate.middle)) {
                testConditon.add(DL.equal_alignment_end);
            }

            boolean duplicateIsShorterOrEqual = maybeDuplicate.middle
                    - maybeDuplicate.left <= recordBuffer.peek().middle - recordBuffer.peek().left;
            boolean duplicateIsLongerOrEqual = recordBuffer.peek().middle
                    - recordBuffer.peek().left <= maybeDuplicate.middle - maybeDuplicate.left;

            if (duplicateIsShorterOrEqual) {
                testConditon.add(DL.maybed_shorter_or_equal);
            }
            if (duplicateIsLongerOrEqual) {
                testConditon.add(DL.maybed_longer_or_equal);
            }

            if (recordBuffer.peek().right.getReadNegativeStrandFlag()) {
                testConditon.add(DL.buffer_reverse_strand);
            } else {
                testConditon.add(DL.buffer_forward_strand);
            }
            if (maybeDuplicate.right.getReadNegativeStrandFlag()) {
                testConditon.add(DL.maybed_reverse_strand);
            } else {
                testConditon.add(DL.maybed_forward_strand);
            }

            //System.out.println("Testing for duplication: "+testConditon);
            //System.out.println(recordBuffer.peek().right.getReadName()+"\t"+recordBuffer.peek().right.getAlignmentStart()+"\t"+recordBuffer.peek().right.getAlignmentEnd());
            //System.out.println(maybeDuplicate.right.getReadName()+"\t"+maybeDuplicate.right.getAlignmentStart()+"\t"+maybeDuplicate.right.getAlignmentEnd());

            //for ( EnumSet<DL> match : duplicateConditionSet.stream().filter(dc -> testConditon.containsAll(dc) ).collect(Collectors.toList()) ) {
            //  System.out.println("Match to: "+match);
            //}
            //for ( EnumSet<DL> match : duplicateConditionSet.stream().collect(Collectors.toList()) ) {
            //  System.out.println("Try to match: "+match);
            //  if ( match.containsAll(testConditon) )
            //  {
            //    System.out.println("success");
            //  }
            //}

            // Test for Duplication
            if (duplicateConditionSet.stream().anyMatch(dc -> testConditon.containsAll(dc))) {
                duplicateBuffer.add(maybeDuplicate);
            }
        }
    }
    //START DEBUG
    /*
    System.out.println ("recordBuffer");
            
    Comparator<SAMRecord> samRecordComparatorForRecordBuffer = new SAMRecordPositionAndQualityComparator();
    ArrayList<ImmutableTriple<Integer, Integer, SAMRecord>> sortedRecordBuffer = new ArrayList<ImmutableTriple<Integer, Integer, SAMRecord>>(recordBuffer.size());
    Iterator<ImmutableTriple<Integer, Integer, SAMRecord>> rit = recordBuffer.iterator();
            
    while (rit.hasNext()) {
    sortedRecordBuffer.add(rit.next());
    }
    sortedRecordBuffer.sort(Comparator.comparing(ImmutableTriple<Integer, Integer, SAMRecord>::getRight, samRecordComparatorForRecordBuffer));
            
    for ( ImmutableTriple<Integer, Integer, SAMRecord> currTriple : sortedRecordBuffer ) {
    System.out.println(" srb: "+(currTriple.right.getReadNegativeStrandFlag()?"-":"+")+" "+currTriple+" "+SAMRecordQualityComparator.getQualityScore(currTriple.right.getBaseQualityString()));
    }
            
    System.out.println ("duplicateBuffer");
    ArrayList<ImmutableTriple<Integer, Integer, SAMRecord>> sortedDuplicateBuffer = new ArrayList<ImmutableTriple<Integer, Integer, SAMRecord>>(duplicateBuffer.size());
    Iterator<ImmutableTriple<Integer, Integer, SAMRecord>> dit = duplicateBuffer.iterator();
    while (dit.hasNext()) {
    sortedDuplicateBuffer.add(dit.next());
    }
    sortedDuplicateBuffer.sort(Comparator.comparing(ImmutableTriple<Integer, Integer, SAMRecord>::getMiddle));
            
    for ( ImmutableTriple<Integer, Integer, SAMRecord> currTriple : sortedDuplicateBuffer ) {
    System.out.println(" dbe: "+(currTriple.right.getReadNegativeStrandFlag()?"-":"+")+" "+currTriple+" "+SAMRecordQualityComparator.getQualityScore(currTriple.right.getBaseQualityString()));
    }
            
    // Sort again with priority queue order
    sortedDuplicateBuffer.sort(Comparator.comparing(ImmutableTriple<Integer, Integer, SAMRecord>::getRight, samRecordComparator.reversed()));
    for ( ImmutableTriple<Integer, Integer, SAMRecord> currTriple : sortedDuplicateBuffer ) {
    System.out.println("sdbe: "+(currTriple.right.getReadNegativeStrandFlag()?"-":"+")+" "+currTriple+" "+SAMRecordQualityComparator.getQualityScore(currTriple.right.getBaseQualityString()));
    }
    */
    //END DEBUG
    if (!duplicateBuffer.isEmpty() && !discardSet.contains(duplicateBuffer.peek().right.getReadName())) {
        //System.out.println("WRITE "+duplicateBuffer.peek());
        decrementDuplicateStats(dupStats, allReadsAsMerged, duplicateBuffer.peek().right.getReadName());
        occurenceCounterMerged.putValue(Long
                .valueOf(duplicateBuffer.stream()
                        .filter(d -> allReadsAsMerged || d.right.getReadName().startsWith("M_")).count())
                .intValue() - 1);
        outputSam.addAlignment(duplicateBuffer.peek().right);
    }
    while (!duplicateBuffer.isEmpty()) {
        discardSet.add(duplicateBuffer.poll().right.getReadName());
    }
    // Maintain the invariant that the first item in recordBuffer may have duplicates
    while (!recordBuffer.isEmpty() && discardSet.contains(recordBuffer.peek().right.getReadName())) {
        String duplicateReadName = recordBuffer.poll().right.getReadName();
        incrementDuplicateStats(dupStats, allReadsAsMerged, duplicateReadName);
        discardSet.remove(duplicateReadName);
    }
}

From source file:com.datatorrent.lib.multiwindow.SortedMovingWindow.java

@SuppressWarnings("unchecked")
@Override/*from   w  w w .  j ava2s.  c o m*/
public void endWindow() {
    super.endWindow();
    tuplesInCurrentStreamWindow = new LinkedList<T>();
    if (lastExpiredWindowState == null) {
        // not ready to emit value or empty in a certain window
        return;
    }
    // Assumption: the expiring tuple and any tuple before are already sorted. So it's safe to emit tuples from sortedListInSlidingWin till the expiring tuple
    for (T expiredTuple : lastExpiredWindowState) {
        // Find sorted list for the given key
        PriorityQueue<T> sortedListForE = sortedListInSlidingWin.get(function.apply(expiredTuple));
        for (Iterator<T> iterator = sortedListForE.iterator(); iterator.hasNext();) {
            T minElemInSortedList = iterator.next();
            int k = 0;
            if (comparator == null) {
                if (expiredTuple instanceof Comparable) {
                    k = ((Comparable<T>) expiredTuple).compareTo(minElemInSortedList);
                } else {
                    errorOutput.emit(expiredTuple);
                    throw new IllegalArgumentException("Operator \""
                            + ClassUtils.getShortClassName(this.getClass()) + "\" encounters an invalid tuple "
                            + expiredTuple + "\nNeither the tuple is comparable Nor Comparator is specified!");
                }
            } else {
                k = comparator.compare(expiredTuple, minElemInSortedList);
            }
            if (k < 0) {
                // If the expiring tuple is less than the first element of the sorted list. No more tuples to emit
                break;
            } else {
                // Emit the element in sorted list if it's less than the expiring tuple
                outputPort.emit(minElemInSortedList);
                // remove the element from the sorted list
                iterator.remove();
            }
        }
    }
}

From source file:net.sourceforge.jasa.market.FourHeapOrderBook.java

@SuppressWarnings("all")
public void prettyPrint(String title, PriorityQueue shouts) {
    logger.info(title);//from  w  ww . j ava 2 s .  c om
    logger.info("--------------");
    Iterator i = shouts.iterator();
    while (i.hasNext()) {
        Order shout = (Order) i.next();
        logger.info(shout.toPrettyString());
    }
    logger.info("");
}

From source file:edu.snu.leader.hidden.MetricSpatialIndividual.java

/**
 * TODO Method description/*ww w .  j  a v  a  2s  .c o  m*/
 *
 * @param simState
 * @see edu.snu.leader.hidden.SpatialIndividual#findNearestNeighbors(edu.snu.leader.hidden.SimulationState)
 */
@Override
public void findNearestNeighbors(SimulationState simState) {
    _LOG.trace("Entering findNearestNeighbors( simState )");

    // Get the metric distance to calculate the nearest neighbors
    _nearestNeighborDistance = simState.getNearestNeighborDistance();

    // Build a priority queue to sort things for us
    PriorityQueue<Neighbor> sortedNeighbors = new PriorityQueue<Neighbor>();

    // Iterate through all the individuals
    Iterator<SpatialIndividual> indIter = simState.getAllIndividuals().iterator();
    while (indIter.hasNext()) {
        // Get the individual
        SpatialIndividual ind = indIter.next();

        // If it is us, continue on
        if (_id.equals(ind._id)) {
            continue;
        }

        // Build a neighbor out of it and put it in the queue
        Neighbor neighbor = new Neighbor((float) _location.distance(ind._location), ind);
        sortedNeighbors.add(neighbor);
    }

    // Get all the neighbors within the specified distance
    Iterator<Neighbor> neighborIter = sortedNeighbors.iterator();
    while (neighborIter.hasNext()) {
        Neighbor neighbor = neighborIter.next();

        // Is it within the distance?
        if (neighbor.getDistance() <= _nearestNeighborDistance) {
            // Yup
            _nearestNeighbors.add(neighbor);
            neighbor.getIndividual().signalNearestNeighborStatus(this);
        }
        //            else
        //            {
        //                // We can bail because the neighbors are sorted by distance
        //                // from closest to farthest
        //                break;
        //            }
    }

    _LOG.trace("Leaving findNearestNeighbors( simState )");

}