Java Code Examples for java.util.ListIterator#previous()

The following examples show how to use java.util.ListIterator#previous() . These examples are extracted from open source projects. 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 Project: qpid-broker-j   File: RangeSetImpl.java    License: Apache License 2.0 6 votes vote down vote up
@Override
public void add(Range range)
{
    ListIterator<Range> it = ranges.listIterator();

    while (it.hasNext())
    {
        Range next = it.next();
        if (range.touches(next))
        {
            it.remove();
            range = range.span(next);
        }
        else if (lt(range.getUpper(), next.getLower()))
        {
            it.previous();
            it.add(range);
            return;
        }
    }

    it.add(range);
}
 
Example 2
@Override
public final Iterator<Object> descendingIterator() {
    final ListIterator<Object> it = listIterator(size());
    return new Iterator<Object>() {
        @Override
        public boolean hasNext() {
            return it.hasPrevious();
        }

        @Override
        public Object next() {
            return it.previous();
        }

        @Override
        public void remove() {
            it.remove();
        }
    };
}
 
Example 3
/**
 * Gets the values that have occurrences closest to given target count.
 * Above the count is always preferred to below the count, but exact is preferred to above.
 * TODO: VERIFY this works.
 */
static Set<String> getClosestValuesByCount(Map<String, Integer> counts, int targetCount) {
    Map<Integer, Set<String>> countMechs = makeCountValueMap(counts);
    if (countMechs.isEmpty()) {
        return Collections.emptySet();
    }
    List<Integer> highToLowCounts = new ArrayList<>(countMechs.keySet());
    Collections.sort(highToLowCounts, Collections.reverseOrder());

    ListIterator<Integer> it = highToLowCounts.listIterator();
    int count = it.next();
    while(it.hasNext() && (count = it.next()) >= targetCount) {
        ;
    }
    if (count >= targetCount) {
        return countMechs.get(count);
    } else {
        it.previous(); // discard to go back one
        if (it.hasPrevious()) {
            return countMechs.get(it.previous());
        } else {
            return countMechs.get(count);
        }
    }
}
 
Example 4
Source Project: sailfish-core   File: FileMessageLoader.java    License: Apache License 2.0 6 votes vote down vote up
@Override
protected void retrieveMessages(Queue<FileMessage> forMessages, int count, long lastID) {
    if(lastID == -1 || lastID == source.size()) {
        return;
    }

    try {
        ListIterator<FileMessage> it = source.listIterator((int)lastID);

        while(count > 0 && (ascending ? it.hasNext() : it.hasPrevious())) {
            FileMessage message = ascending ? it.next() : it.previous();

            if(!checkMessage(message, filter)) {
                continue;
            }

            forMessages.add(message);
            count--;
        }

        nextIndex = ascending ? it.nextIndex() : it.previousIndex();
    } catch(IndexOutOfBoundsException | NoSuchElementException e) {
        throw new StorageException("Message list probably have been cleared", e);
    }
}
 
Example 5
Source Project: Mupdf   File: DocPageView.java    License: Apache License 2.0 6 votes vote down vote up
public NoteAnnotation getSelectedNoteAnnotation()
{
	if (mAnnotations != null)
	{
		//  iterate in reverse order
		ListIterator<PageAnnotation> li = mAnnotations.listIterator(mAnnotations.size());
		while (li.hasPrevious())
		{
			PageAnnotation annot = li.previous();
			if ((annot instanceof NoteAnnotation) && annot.isSelected())
			{
				return (NoteAnnotation)annot;
			}
		}
	}

	return null;
}
 
Example 6
Source Project: j2objc   File: ICUService.java    License: Apache License 2.0 6 votes vote down vote up
/**
 * Return a map from visible ids to factories.
 */
private Map<String, Factory> getVisibleIDMap() {
    synchronized (this) { // or idcache-only lock?
        if (idcache == null) {
            try {
                factoryLock.acquireRead();
                Map<String, Factory> mutableMap = new HashMap<String, Factory>();
                ListIterator<Factory> lIter = factories.listIterator(factories.size());
                while (lIter.hasPrevious()) {
                    Factory f = lIter.previous();
                    f.updateVisibleIDs(mutableMap);
                }
                this.idcache = Collections.unmodifiableMap(mutableMap);
            } finally {
                factoryLock.releaseRead();
            }
        }
    }
    return idcache;
}
 
Example 7
Source Project: es6draft   File: ExpressionGenerator.java    License: MIT License 6 votes vote down vote up
private int arrayLiteral(ListIterator<Expression> iterator, CodeVisitor mv) {
    int nextIndex = 0;
    while (iterator.hasNext()) {
        Expression element = iterator.next();
        if (element instanceof Elision) {
            // Elision
        } else if (element instanceof SpreadElement) {
            iterator.previous(); // step back
            break;
        } else {
            mv.dup();
            mv.iconst(nextIndex);
            ArrayAccumulationElement(element, mv);
        }
        nextIndex += 1;
    }
    return nextIndex;
}
 
Example 8
Source Project: immutables   File: Code.java    License: Apache License 2.0 6 votes vote down vote up
static List<Term> replaceReturn(List<Term> code, String replacement) {
  ArrayList<Term> result = new ArrayList<>(code);
  ListIterator<Term> it = result.listIterator();
  boolean wasReturn = false;
  while (it.hasNext()) {
    Term t = it.next();
    if (t.isWordOrNumber() && t.is("return")) {
      it.set(new Other(replacement));
      wasReturn = true;
    }
  }
  if (!wasReturn) {
    ListIterator<Term> revIt = Lists.reverse(result).listIterator();
    if (nextNonBlankIs(revIt, "}")) {
      nextNonBlankIs(revIt, ";");
      revIt.previous();
      revIt.add(new Delimiter(";"));
      revIt.add(new Other(replacement));
      revIt.add(new Whitespace("\n"));
    }
  }
  return result;
}
 
Example 9
void add(DelimiterProcessor dp) {
    final int len = dp.getMinLength();
    ListIterator<DelimiterProcessor> it = processors.listIterator();
    boolean added = false;
    while (it.hasNext()) {
        DelimiterProcessor p = it.next();
        int pLen = p.getMinLength();
        if (len > pLen) {
            it.previous();
            it.add(dp);
            added = true;
            break;
        } else if (len == pLen) {
            throw new IllegalArgumentException("Cannot add two delimiter processors for char '" + delim + "' and minimum length " + len);
        }
    }
    if (!added) {
        processors.add(dp);
        this.minLength = len;
    }
}
 
Example 10
@Test
public void indexedListIteratorInMiddleHasNextAndHasPreviousOnThreeElementsList_shouldReturnTrueForEachElement() {
    final ObservableArrayList<String> list = new ObservableArrayList<>("1", "2", "3");
    final ListIterator<String> iterator = list.listIterator(1);

    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.hasPrevious(), is(true));
    iterator.next();
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.hasPrevious(), is(true));
    iterator.next();
    assertThat(iterator.hasNext(), is(false));
    assertThat(iterator.hasPrevious(), is(true));
    iterator.previous();
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.hasPrevious(), is(true));
    iterator.previous();
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.hasPrevious(), is(true));
    iterator.previous();
    assertThat(iterator.hasNext(), is(true));
    assertThat(iterator.hasPrevious(), is(false));
}
 
Example 11
Source Project: scipio-erp   File: FormRenderer.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * SCIPIO: Renders the given modelFormField (within the open cell) if it passes shouldUse condition;
 * in addition, if the following fields have the same name, they are also rendered and
 * consumed from the formFieldsIt list iterator.
 * <p>
 * This is needed because we could have several fields of same name
 * in a row with different use-when expressions. In such case, we must render
 * exactly one cell for all of them (at most one, but one is always required also).
 * We must process the fields having same name as a "batch" here.
 * <p>
 * Added 2018-03-02.
 */
private void renderItemRowCellFields(Appendable writer, Map<String, Object> localContext, FormStringRenderer formStringRenderer,
        ModelFormField modelFormField, ListIterator<ModelFormField> formFieldsIt, boolean forceUse) throws IOException {
    List<ModelFormField> sameNameFields = null;
    String modelFormFieldName = modelFormField.getName();
    while(formFieldsIt.hasNext()) {
        ModelFormField nextField = formFieldsIt.next();
        if (modelFormFieldName.equals(nextField.getName())) {
            if (sameNameFields == null) sameNameFields = new ArrayList<>();
            sameNameFields.add(nextField);
        } else {
            formFieldsIt.previous();
            break;
        }
    }

    if (forceUse || modelFormField.shouldUse(localContext)) {
        modelFormField.renderFieldString(writer, localContext, formStringRenderer);
    }
    if (sameNameFields != null) {
        for(ModelFormField sameNameField : sameNameFields) {
            if (forceUse || sameNameField.shouldUse(localContext)) {
                sameNameField.renderFieldString(writer, localContext, formStringRenderer);
            }
        }
    }
}
 
Example 12
Source Project: flink   File: CompletedCheckpointStore.java    License: Apache License 2.0 5 votes vote down vote up
/**
 * Returns the latest {@link CompletedCheckpoint} instance or <code>null</code> if none was
 * added.
 */
default CompletedCheckpoint getLatestCheckpoint(boolean isPreferCheckpointForRecovery) throws Exception {
	if (getAllCheckpoints().isEmpty()) {
		return null;
	}

	CompletedCheckpoint candidate = getAllCheckpoints().get(getAllCheckpoints().size() - 1);
	if (isPreferCheckpointForRecovery && getAllCheckpoints().size() > 1) {
		List<CompletedCheckpoint> allCheckpoints;
		try {
			allCheckpoints = getAllCheckpoints();
			ListIterator<CompletedCheckpoint> listIterator = allCheckpoints.listIterator(allCheckpoints.size() - 1);
			while (listIterator.hasPrevious()) {
				CompletedCheckpoint prev = listIterator.previous();
				if (!prev.getProperties().isSavepoint()) {
					candidate = prev;
					LOG.info("Found a completed checkpoint before the latest savepoint, will use it to recover!");
					break;
				}
			}
		} catch (Exception e) {
			LOG.error("Method getAllCheckpoints caused exception : ", e);
			throw new FlinkRuntimeException(e);
		}
	}

	return candidate;
}
 
Example 13
@Override
public Iterator<Policy> iterator() {
    final ListIterator<Policy> listIterator = policies.listIterator(policies.size());
    return new Iterator<Policy>() {
        @Override
        public boolean hasNext() { return listIterator.hasPrevious(); }

        @Override
        public Policy next() { return listIterator.previous(); }

        @Override
        public void remove() { listIterator.remove(); }
    };
}
 
Example 14
Source Project: servicecomb-pack   File: TxEntities.java    License: Apache License 2.0 5 votes vote down vote up
public void forEachReverse(BiConsumer<String, TxEntity> action) {
  ListIterator<Map.Entry<String, TxEntity>> iterator = new ArrayList<>(entities.entrySet()).listIterator(entities.size());
  while (iterator.hasPrevious()) {
    Map.Entry<String, TxEntity> entry = iterator.previous();
    action.accept(entry.getKey(),entry.getValue());
  }
}
 
Example 15
Source Project: sakai   File: Revision.java    License: Educational Community License v2.0 5 votes vote down vote up
/**
 * Applies the series of deltas in this revision as patches to
 * the given text.
 * @param target the text to patch.
 * @throws PatchFailedException if any of the patches cannot be applied.
 */
public synchronized void applyTo(List target) throws PatchFailedException
{
    ListIterator i = deltas_.listIterator(deltas_.size());
    while (i.hasPrevious())
    {
        Delta delta = (Delta) i.previous();
        delta.patch(target);
    }
}
 
Example 16
/**
 * Releases for normal dispatching to the current focus owner all
 * KeyEvents which were enqueued because of a call to
 * <code>enqueueKeyEvents</code> with the same timestamp and Component.
 * If the given timestamp is less than zero, the outstanding enqueue
 * request for the given Component with the <b>oldest</b> timestamp (if
 * any) should be cancelled.
 *
 * @param after the timestamp specified in the call to
 *        <code>enqueueKeyEvents</code>, or any value < 0
 * @param untilFocused the Component specified in the call to
 *        <code>enqueueKeyEvents</code>
 * @see #enqueueKeyEvents
 * @see #discardKeyEvents
 */
protected synchronized void dequeueKeyEvents(long after,
                                             Component untilFocused) {
    if (untilFocused == null) {
        return;
    }

    focusLog.finer("Dequeue at {0} for {1}",
                   after, untilFocused);

    TypeAheadMarker marker;
    ListIterator iter = typeAheadMarkers.listIterator
        ((after >= 0) ? typeAheadMarkers.size() : 0);

    if (after < 0) {
        while (iter.hasNext()) {
            marker = (TypeAheadMarker)iter.next();
            if (marker.untilFocused == untilFocused)
            {
                iter.remove();
                return;
            }
        }
    } else {
        while (iter.hasPrevious()) {
            marker = (TypeAheadMarker)iter.previous();
            if (marker.untilFocused == untilFocused &&
                marker.after == after)
            {
                iter.remove();
                return;
            }
        }
    }
}
 
Example 17
/**
 * Look for single edits surrounded on both sides by equalities
 * which can be shifted sideways to align the edit to a word boundary.
 * e.g: The c&lt;ins&gt;at c&lt;/ins&gt;ame. -&gt; The &lt;ins&gt;cat &lt;/ins&gt;came.
 * @param diffs LinkedList of Diff objects.
 */
public void diff_cleanupSemanticLossless(LinkedList<Diff> diffs) {
    String equality1, edit, equality2;
    String commonString;
    int commonOffset;
    int score, bestScore;
    String bestEquality1, bestEdit, bestEquality2;
    // Create a new iterator at the start.
    ListIterator<Diff> pointer = diffs.listIterator();
    Diff prevDiff = pointer.hasNext() ? pointer.next() : null;
    Diff thisDiff = pointer.hasNext() ? pointer.next() : null;
    Diff nextDiff = pointer.hasNext() ? pointer.next() : null;
    // Intentionally ignore the first and last element (don't need checking).
    while (nextDiff != null) {
        if (prevDiff.operation == Operation.EQUAL &&
                nextDiff.operation == Operation.EQUAL) {
            // This is a single edit surrounded by equalities.
            equality1 = prevDiff.text;
            edit = thisDiff.text;
            equality2 = nextDiff.text;

            // First, shift the edit as far left as possible.
            commonOffset = diff_commonSuffix(equality1, edit);
            if (commonOffset != 0) {
                commonString = edit.substring(edit.length() - commonOffset);
                equality1 = equality1.substring(0, equality1.length() - commonOffset);
                edit = commonString + edit.substring(0, edit.length() - commonOffset);
                equality2 = commonString + equality2;
            }

            // Second, step character by character right, looking for the best fit.
            bestEquality1 = equality1;
            bestEdit = edit;
            bestEquality2 = equality2;
            bestScore = diff_cleanupSemanticScore(equality1, edit)
                    + diff_cleanupSemanticScore(edit, equality2);
            while (edit.length() != 0 && equality2.length() != 0
                    && edit.charAt(0) == equality2.charAt(0)) {
                equality1 += edit.charAt(0);
                edit = edit.substring(1) + equality2.charAt(0);
                equality2 = equality2.substring(1);
                score = diff_cleanupSemanticScore(equality1, edit)
                        + diff_cleanupSemanticScore(edit, equality2);
                // The >= encourages trailing rather than leading whitespace on edits.
                if (score >= bestScore) {
                    bestScore = score;
                    bestEquality1 = equality1;
                    bestEdit = edit;
                    bestEquality2 = equality2;
                }
            }

            if (!prevDiff.text.equals(bestEquality1)) {
                // We have an improvement, save it back to the diff.
                if (bestEquality1.length() != 0) {
                    prevDiff.text = bestEquality1;
                } else {
                    pointer.previous(); // Walk past nextDiff.
                    pointer.previous(); // Walk past thisDiff.
                    pointer.previous(); // Walk past prevDiff.
                    pointer.remove(); // Delete prevDiff.
                    pointer.next(); // Walk past thisDiff.
                    pointer.next(); // Walk past nextDiff.
                }
                thisDiff.text = bestEdit;
                if (bestEquality2.length() != 0) {
                    nextDiff.text = bestEquality2;
                } else {
                    pointer.remove(); // Delete nextDiff.
                    nextDiff = thisDiff;
                    thisDiff = prevDiff;
                }
            }
        }
        prevDiff = thisDiff;
        thisDiff = nextDiff;
        nextDiff = pointer.hasNext() ? pointer.next() : null;
    }
}
 
Example 18
private byte[] readClusters(List<Long> clusters)
{
    int maxLength = 16384; // Linux/libusb internally can only handle a buffer of 16834 for bulk transfers
    int maxClusters = (int) (maxLength / (reservedRegion.getBytesPerSector() * reservedRegion.getSectorsPerCluster()));
    long firstClusterLba = partition.getLbaStart() + reservedRegion.getNumberReservedSectors()
            + (reservedRegion.getFatCopies() * reservedRegion.getNumberSectorsPerFat());

    int lengthData = clusters.size() * ((int) (reservedRegion.getSectorsPerCluster() * reservedRegion.getBytesPerSector()));
    byte[] data = new byte[lengthData];

    ListIterator<Long> e = clusters.listIterator();
    int pointer = 0;

    while(e.hasNext())
    {
        long cluster = e.next();
        int i = 1;
        boolean keep = true;
        while(i < maxClusters && keep)
        {
            if(e.hasNext())
            {
                if(cluster == e.next() - i)
                    i++;
                else
                {
                    if(e.hasPrevious())
                        e.previous();
                    keep = false;
                }
            }else
            {
                keep = false;
            }
        }

        long lbaCluster = firstClusterLba + (cluster - 2) * reservedRegion.getSectorsPerCluster();
        int clustersLength = i *  (int) (reservedRegion.getSectorsPerCluster());
        int bufferLength = clustersLength * ((int) reservedRegion.getBytesPerSector());

        byte[] rawClusters = readBytes(lbaCluster, clustersLength);
        if(rawClusters == null)
            return null;

        System.arraycopy(rawClusters, 0, data, pointer, bufferLength);

        pointer += bufferLength;
    }
    return data;
}
 
Example 19
Source Project: MHAP   File: RandomSequenceGenerator.java    License: Apache License 2.0 4 votes vote down vote up
public String addError(String str, double insertionRate, double deletionRate, double substitutionRate)
{
	if (insertionRate < 0.0 || deletionRate < 0.0 || substitutionRate < 0.0)
		throw new MhapRuntimeException("Error rate cannot be negative.");
	
	if (insertionRate+deletionRate+substitutionRate>1.00001)
		throw new MhapRuntimeException("Error rate must be less than or equal to 1.0.");

	double errorRate = insertionRate + deletionRate + substitutionRate;

	// use a linked list for insertions
	LinkedList<Character> modifiedSequence = new LinkedList<>();
	for (char a : str.toCharArray())
		modifiedSequence.add(a);

	// now mutate
	ListIterator<Character> iter = modifiedSequence.listIterator();
	while (iter.hasNext())
	{
		char i = iter.next();

		if (randGenerator.nextDouble() < errorRate)
		{
			double errorType = randGenerator.nextDouble();
			if (errorType < substitutionRate)
			{ // mismatch
				// switch base

				iter.set(getRandomBase(i));

				i++;
			}
			else if (errorType < insertionRate + substitutionRate)
			{ // insert

				iter.previous();
				iter.add(getRandomBase(null));
			}
			else
			{ // delete

				iter.remove();
			}
		}
		else
		{
			// i++;
		}
	}

	StringBuilder returnedString = new StringBuilder(modifiedSequence.size());
	for (char c : modifiedSequence)
		returnedString.append(c);

	return returnedString.toString();
}
 
Example 20
/**
 * Look for single edits surrounded on both sides by equalities
 * which can be shifted sideways to align the edit to a word boundary.
 * e.g: The c<ins>at c</ins>ame. -> The <ins>cat </ins>came.
 * @param diffs LinkedList of Diff objects.
 */
public void diff_cleanupSemanticLossless(LinkedList<Diff> diffs) {
	String equality1, edit, equality2;
	String commonString;
	int commonOffset;
	int score, bestScore;
	String bestEquality1, bestEdit, bestEquality2;
	// Create a new iterator at the start.
	ListIterator<Diff> pointer = diffs.listIterator();
	Diff prevDiff = pointer.hasNext() ? pointer.next() : null;
	Diff thisDiff = pointer.hasNext() ? pointer.next() : null;
	Diff nextDiff = pointer.hasNext() ? pointer.next() : null;
	// Intentionally ignore the first and last element (don't need checking).
	while (nextDiff != null) {
		if (prevDiff.operation == Operation.EQUAL &&
			nextDiff.operation == Operation.EQUAL) {
			// This is a single edit surrounded by equalities.
			equality1 = prevDiff.text;
			edit = thisDiff.text;
			equality2 = nextDiff.text;

			// First, shift the edit as far left as possible.
			commonOffset = diff_commonSuffix(equality1, edit);
			if (commonOffset != 0) {
				commonString = edit.substring(edit.length() - commonOffset);
				equality1 = equality1.substring(0, equality1.length() - commonOffset);
				edit = commonString + edit.substring(0, edit.length() - commonOffset);
				equality2 = commonString + equality2;
			}

			// Second, step character by character right, looking for the best fit.
			bestEquality1 = equality1;
			bestEdit = edit;
			bestEquality2 = equality2;
			bestScore = diff_cleanupSemanticScore(equality1, edit)
				+ diff_cleanupSemanticScore(edit, equality2);
			while (edit.length() != 0 && equality2.length() != 0
				   && edit.charAt(0) == equality2.charAt(0)) {
				equality1 += edit.charAt(0);
				edit = edit.substring(1) + equality2.charAt(0);
				equality2 = equality2.substring(1);
				score = diff_cleanupSemanticScore(equality1, edit)
					+ diff_cleanupSemanticScore(edit, equality2);
				// The >= encourages trailing rather than leading whitespace on edits.
				if (score >= bestScore) {
					bestScore = score;
					bestEquality1 = equality1;
					bestEdit = edit;
					bestEquality2 = equality2;
				}
			}

			if (!prevDiff.text.equals(bestEquality1)) {
				// We have an improvement, save it back to the diff.
				if (bestEquality1.length() != 0) {
					prevDiff.text = bestEquality1;
				} else {
					pointer.previous(); // Walk past nextDiff.
					pointer.previous(); // Walk past thisDiff.
					pointer.previous(); // Walk past prevDiff.
					pointer.remove(); // Delete prevDiff.
					pointer.next(); // Walk past thisDiff.
					pointer.next(); // Walk past nextDiff.
				}
				thisDiff.text = bestEdit;
				if (bestEquality2.length() != 0) {
					nextDiff.text = bestEquality2;
				} else {
					pointer.remove(); // Delete nextDiff.
					nextDiff = thisDiff;
					thisDiff = prevDiff;
				}
			}
		}
		prevDiff = thisDiff;
		thisDiff = nextDiff;
		nextDiff = pointer.hasNext() ? pointer.next() : null;
	}
}