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

The following examples show how to use java.util.ListIterator#previous() . 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: StaggeredDelimiterProcessor.java    From Markwon with Apache License 2.0 6 votes vote down vote up
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 2
Source File: ListAdapter.java    From openjdk-8-source with GNU General Public License v2.0 6 votes vote down vote up
@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
Source File: TestObservableArrayListIterators.java    From dolphin-platform with Apache License 2.0 6 votes vote down vote up
@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 4
Source File: Code.java    From immutables with 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 5
Source File: ContactMechPurposeInfo.java    From scipio-erp with Apache License 2.0 6 votes vote down vote up
/**
 * 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 6
Source File: FileMessageLoader.java    From sailfish-core with 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 7
Source File: DocPageView.java    From Mupdf with 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 8
Source File: ExpressionGenerator.java    From es6draft with 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 9
Source File: RangeSetImpl.java    From qpid-broker-j with 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 10
Source File: ICUService.java    From j2objc with 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 11
Source File: ResponsePolicyChain.java    From gravitee-gateway with Apache License 2.0 5 votes vote down vote up
@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 12
Source File: DefaultKeyboardFocusManager.java    From jdk-1.7-annotated with Apache License 2.0 5 votes vote down vote up
/**
 * 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 13
Source File: Revision.java    From sakai with 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 14
Source File: TxEntities.java    From servicecomb-pack with 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 File: CompletedCheckpointStore.java    From flink with 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 16
Source File: FormRenderer.java    From scipio-erp with 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 17
Source File: RandomSequenceGenerator.java    From MHAP with 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 18
Source File: DiffMatchPatch.java    From PowerFileExplorer with GNU General Public License v3.0 4 votes vote down vote up
/**
 * 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;
	}
}
 
Example 19
Source File: FATHandler.java    From Pincho-Usb-Mass-Storage-for-Android with MIT License 4 votes vote down vote up
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 20
Source File: diff_match_patch.java    From dsl-compiler-client with BSD 3-Clause "New" or "Revised" License 4 votes vote down vote up
/**
 * 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;
    }
}