22
Nov

Forward / backward List iteration in java

Iterate a list in forward / backward direction
================================================

Iterator allows forward only iteration.  eg.

		List<Integer> li = new ArrayList<Integer>();
		li.add(23);
		li.add(98);
		li.add(29);
		li.add(71);
		li.add(5);
		
		
		Iterator<Integer> itr = li.iterator();
		
		while(itr.hasNext()) {
			Integer listElement = itr.next();
			System.out.println(listElement);
			
			Integer listPre = itr.previous(); // There is no such thing 
		}


In order to support forward and backward iteration, Collections support ListIterator as follow:


		List<Integer> li = new ArrayList<Integer>();
		li.add(23);
		li.add(98);
		li.add(29);
		li.add(71);
		li.add(5);

		ListIterator<Integer> litr = li.listIterator();

		System.out.println("Elements in forward directiton");
		while (litr.hasNext()) {
			System.out.println(litr.next());
		}
		System.out.println("Elements in backward directiton");
		while (litr.hasPrevious()) {
			System.out.println(litr.previous());
		}


Output:
Elements in forward directiton
23
98
29
71
5
Elements in backward directiton
5
71
29
98
23