All Downloads are FREE. Search and download functionalities are using the official Maven repository.

net.sf.okapi.common.ReversedIterator Maven / Gradle / Ivy

There is a newer version: 1.46.0
Show newest version
/*===========================================================================
  Copyright (C) 2010 by the Okapi Framework contributors
-----------------------------------------------------------------------------
  Licensed under the Apache License, Version 2.0 (the "License");
  you may not use this file except in compliance with the License.
  You may obtain a copy of the License at

  http://www.apache.org/licenses/LICENSE-2.0

  Unless required by applicable law or agreed to in writing, software
  distributed under the License is distributed on an "AS IS" BASIS,
  WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
  See the License for the specific language governing permissions and
  limitations under the License.
===========================================================================*/

package net.sf.okapi.common;

import java.util.Iterator;
import java.util.List;
import java.util.ListIterator;

/**
 * Create a reversed iterator for a list compatible with foreach. Credit: Nat on
 * http://stackoverflow.com/questions/1098117/can-one-do-a-for-each-loop-in-java-in-reverse-orders
 * 
 * @author HARGRAVEJE
 * 
 * @param 
 *            type of the list element
 */
public class ReversedIterator implements Iterable {
	private final List original;

	public ReversedIterator(final List original) {
		this.original = original;
	}

	public Iterator iterator() {
		final ListIterator i = original.listIterator(original.size());

		return new Iterator() {
			public boolean hasNext() {
				return i.hasPrevious();
			}

			public T next() {
				return i.previous();
			}

			public void remove() {
				i.remove();
			}
		};
	}
	
	public static  ReversedIterator reverse(List original) {
        return new ReversedIterator<>(original);
    }

}




© 2015 - 2024 Weber Informatics LLC | Privacy Policy