Iterator in Java

iterator

Iterators are used in the Collection framework in Java( ArrayList, LinkedList, HashMap, etc. ) to iterate the elements one by one.

There are three types:

  • Enumeration
  • Iterator
  • List Iterator

Enumeration Example:

package com.clarifyall.iterator;

public class IteratorEnum {

	enum Vehicles {
		CAR, ZEEP, BUS, TRAIN;
	}

	public static class Test {
		public static void main(String[] args) {
			Vehicles vehicle = Vehicles.BUS;
			System.out.println(vehicle);
		}
	}

}

OUTPUT :

BUS

Iterator Example:

The iterator() method is used to get an Iterator for any collection:

package com.clarifyall.iterator;

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

public class IteratorExample {

	public static void main(String args[]) {

		ArrayList<String> animalsList = new ArrayList<>();

		animalsList.add("Dog");
		animalsList.add("Cat");
		animalsList.add("Lion");
		animalsList.add("Monkey");

		// here we are using iterator() method
		Iterator<String> it = animalsList.iterator();

		while (it.hasNext()) {
			String singleAnimal = (String) it.next();
			System.out.println(singleAnimal);
		}
	}

}

OUTPUT:

Dog
Cat
Lion
Monkey

List Iterator Example:

The listIterator() method is used to get an Iterator for any collection:

package com.clarifyall.iterator;

import java.util.ArrayList;
import java.util.ListIterator;

public class ListIteratorExample {

	public static void main(String args[]) {

		ArrayList<String> animalsList = new ArrayList<>();

		animalsList.add("Dog");
		animalsList.add("Cat");
		animalsList.add("Lion");
		animalsList.add("Monkey");

		// here we are using listIterator() method
		ListIterator<String> it = animalsList.listIterator();

		while (it.hasNext()) {
			String singleAnimal = (String) it.next();
			System.out.println(singleAnimal);
		}
	}

}

OUTPUT:

Dog
Cat
Lion
Monkey

Download Source Code :

About Manohar

I, Manohar am the founder and chief editor of ClarifyAll.com. I am working in an IT professional.

View all posts by Manohar →

Leave a Reply