Rabu, 09 Maret 2016

How to Iterate ArrayList using Java ListIterator Example

1.Basic Java example program to iterate arraylist elements using list iterator
  1. package com.javaIteratearraylistiterator;
  2.  
  3. import java.util.ArrayList;
  4. import java.util.Collections;
  5. import java.util.Iterator;
  6.  
  7. public class IterateListIteratorArrayList{
  8.  
  9. public static void main(String[] args) {
  10.   
  11. //create an ArrayList object
  12. ArrayList<String> arrayList = new ArrayList();
  13.        
  14. //Add elements to Arraylist
  15.  
  16. arrayList.add("A");
  17. arrayList.add("B");
  18. arrayList.add("C");
  19. arrayList.add("D");
  20. arrayList.add("F");
  21. arrayList.add("F");
  22. arrayList.add("G");
  23. arrayList.add("H");
  24. arrayList.add("I");
  25.     
  26.         
  27.  /*
  28. Get a ListIterator object for ArrayList using
  29. istIterator() method.
  30. */
  31.  
  32. ListIterator itr = arrayList.listIterator();
  33.        
  34. /*
  35. Use hasNext() and next() methods of ListIterator to iterate through
  36. the elements in forward direction.
  37. */
  38.  
  39. System.out.println("Iterating through ArrayList elements in forward  direction...");
  40.  
  41. while(itr.hasNext())
  42. System.out.println(itr.next());
  43.      
  44. /*Use hasPrevious() and previous() methods of ListIterator to iterate through
  45. the elements in backward direction.*/
  46.  
  47. System.out.println("Iterating through ArrayList elements in backward   direction...");
  48.         
  49.  
  50. while(itr.hasPrevious())
  51. System.out.println(itr.previous()); 
  52.   
  53. }
  54.  
  55. }
     



Output:

  1. Iterating through ArrayList elements in forward  direction...
  2. A
  3. B
  4. C
  5. D
  6. F
  7. F
  8. G
  9. H
  10. I
  11. Iterating through ArrayList elements in backward   direction...
  12. I
  13. H
  14. G
  15. F
  16. F
  17. D
  18. C
  19. B
  20. A

Bagikan

Jangan lewatkan

How to Iterate ArrayList using Java ListIterator Example
4/ 5
Oleh

Subscribe via email

Suka dengan artikel di atas? Tambahkan email Anda untuk berlangganan.