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:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 |
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 :
1 |
BUS |
Iterator Example:
The iterator() method is used to get an Iterator for any collection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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:
1 2 3 4 |
Dog Cat Lion Monkey |
List Iterator Example:
The listIterator() method is used to get an Iterator for any collection:
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 |
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:
1 2 3 4 |
Dog Cat Lion Monkey |
Download Source Code :
Great Job! and Thanks a lot