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

/**
 * Examples of using List Iterators
 * 
 * @author CSCI209
 */
public class ListIteratorExamples {

	/**
	 * Condition (we are using this for the items that we want to keep in our
	 * list).
	 * 
	 * @param value the value to consider
	 * @return true if the value is evenly divisible by 2
	 */
	public static boolean condition(int value) {
		return value % 2 == 0;
	}

	/**
	 * Display the given list, starting with the header.
	 *
	 * @param myList the list to be displayed
	 * @param header the header to display the list
	 */
	private static void displayList(List<Integer> myList, String header) {
		System.out.println(header);
		for (Integer i : myList) {
			System.out.println(i);
		}
	}

	public static void main(String[] args) {
	    
	    Random numberGenerator = new Random();

		// set up a list
		List<Integer> myList = new ArrayList<>();
		for (int i = 0; i < 10; i++) {
			myList.add(numberGenerator.nextInt());
		}

		displayList(myList, "Original List:");
		System.out.println();

		Iterator<Integer> iter = myList.iterator();

		while (iter.hasNext()) {
			Integer item = iter.next();
			if (!condition(item)) {
				// alternatively, could mutate this object, if the object has
				// mutator methods available.
				// Can't replace this item or remove the item and add in a new
				// object.
				iter.remove();
			}
		}

		displayList(myList, "Next List:");
		
		ListIterator<Integer> iter2 = myList.listIterator(myList.size());
		int counter = myList.size();
		while( iter2.hasPrevious() ) {
		    iter2.previous();
		    if( counter % 2 == 0 ) {
		        iter2.add(counter);
		    }
		    counter--;
		}
		
		System.out.println();
		displayList(myList, "Final List:");

	}

}
