Iterator Example in Java

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

public class IteratorExample {
	public static void main(String a[]) {
		List<Integer> list = new ArrayList<Integer>();
		list.add(34);
		list.add(123);
		list.add(10);
		list.add(56);
		list.add(89);
		list.add(50);

		Iterator<Integer> iterator = list.iterator();
		//Iterating elements from list
		System.out.println("Iterating elements from list: ");
		while (iterator.hasNext()) {
			System.out.println(iterator.next());
		}
		
		System.out.println("List before removing 123: "+list);
		// remove element 123 from list
		iterator = list.iterator();
		while (iterator.hasNext()) {
			if (iterator.next() == 123) {
				iterator.remove();
				break;
			}
		}
		System.out.println("List after removing 123: "+list);
	}
}
Output
Iterating elements from list: 34 123 10 56 89 50 List before removing 123: [34, 123, 10, 56, 89, 50] List after removing 123: [34, 10, 56, 89, 50]










Related Examples


Write a Comparable to compare students based upon their age?
Simple Array Sorting Program
Write a program to convert from decimal to binary?
Write a program to get list of all the files from a given directory?
Producer Consumer Example in Thread
Write a program to reverse a String?
Write a Comparator to compare students based upon their name and age?








Receive Latest Java Examples in Your Email: