Traverse the List Elements Using Next() And HasNext() Methods in Java

You are currently viewing Traverse the List Elements Using Next() And HasNext() Methods in Java

Traverse the List elements using next() and hasNext() methods in Java

import java.util.*;

public class ListExample {
  public static void main(String[] args) {
    //creating a list of integers
    List < Integer > int_list = new ArrayList < Integer > ();

    int count = 0; //variable to count total traversed elements 

    //adding some of the elements
    int_list.add(10);
    int_list.add(20);
    int_list.add(30);
    int_list.add(40);
    int_list.add(50);

    //printing elements
    System.out.println("List elements are...");
    //creating iterator
    Iterator < Integer > it = int_list.iterator();
    while (it.hasNext()) {
      System.out.println(it.next());
      count += 1;
    }
    System.out.println("Total traversed elements are: " + count);
  }
};

Output

List elements are...
10
20
30
40
50
Total traversed elements are: 5

Ranjith

Hi, I'm Manoj a full-time Blogger, YouTuber, Affiliate Marketer, & founder of Coding Diksha. Here, I post about programming to help developers.

Leave a Reply