abhimanyu081
11/12/2018 - 2:45 PM

iterators

iterators

import java.util.LinkedList;
import java.util.List;
import java.util.ListIterator;

public class ListIteratorExample {

	public static void main(String[] args) {

		List<String> cityList = new LinkedList<String>();
		cityList.add("Delhi");
		cityList.add("Agra");
		cityList.add("Bangalore");
		cityList.add("Kerala");
		cityList.add("Pune");

		ListIterator<String> lit = cityList.listIterator();

		// Iterator Example Forward Direction
		System.out.println("**Iterating cityList Forward Direction**");
		while (lit.hasNext()) {

			String cityName = lit.next();
			System.out.println(cityName);

		}
		
		// Iterator Example Backward Direction
		ListIterator<String> litBack = cityList.listIterator(cityList.size()-1); //start iterator from the end of the list
		System.out.println("**Iterating cityList Backward Direction**");
		while (litBack.hasPrevious()) {

			String cityName = litBack.previous();
			System.out.println(cityName);

		}
		
		//ListIterator add/set demo
		lit = cityList.listIterator(); //start again from beginning
		System.out.println("Original List :: "+cityList);
		while (lit.hasNext()) {

			String cityName = lit.next();
			
			if(cityName.equalsIgnoreCase("Delhi")) {
				lit.set("New Delhi"); //replaces an element
			}
			
			if(cityName.equalsIgnoreCase("Kerala")) {
				lit.remove(); // removes element from list
			}
			
			if(cityName.equalsIgnoreCase("Pune")) {
				lit.add("Hydrabad");//add city to the end of the list
			}
		
			System.out.println(cityName);

		}
		System.out.println("Mofdified List :: "+cityList);
	}

}