1.Basic Java example program to iterate arraylist elements using list iterator
Output:
- package com.javaIteratearraylistiterator;
- import java.util.ArrayList;
- import java.util.Collections;
- import java.util.Iterator;
- public class IterateListIteratorArrayList{
- public static void main(String[] args) {
- //create an ArrayList object
- ArrayList<String> arrayList = new ArrayList();
- //Add elements to Arraylist
- arrayList.add("A");
- arrayList.add("B");
- arrayList.add("C");
- arrayList.add("D");
- arrayList.add("F");
- arrayList.add("F");
- arrayList.add("G");
- arrayList.add("H");
- arrayList.add("I");
- /*
- Get a ListIterator object for ArrayList using
- istIterator() method.
- */
- ListIterator itr = arrayList.listIterator();
- /*
- Use hasNext() and next() methods of ListIterator to iterate through
- the elements in forward direction.
- */
- System.out.println("Iterating through ArrayList elements in forward direction...");
- while(itr.hasNext())
- System.out.println(itr.next());
- /*Use hasPrevious() and previous() methods of ListIterator to iterate through
- the elements in backward direction.*/
- System.out.println("Iterating through ArrayList elements in backward direction...");
- while(itr.hasPrevious())
- System.out.println(itr.previous());
- }
- }
Output:
- Iterating through ArrayList elements in forward direction...
- A
- B
- C
- D
- F
- F
- G
- H
- I
- Iterating through ArrayList elements in backward direction...
- I
- H
- G
- F
- F
- D
- C
- B
- A
Bagikan
How to Iterate ArrayList using Java ListIterator Example
4/
5
Oleh
Kris Kimcil