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

Here, we are going to learn how to traverse elements of a List using next() and hasNext() method in Java?
Submitted by IncludeHelp, on October 10, 2018

Given a List of integers and we have to traverse, print all its element using next() and hasNext() methods.

What are hasNex() and next() methods?

Both are the library methods of java.util.Scanner class.

Method hasNext() returns 'true'/'false' - If collection has more values/elements, it returns true otherwise it returns false.

Method next() returns the next element in the collection.

Note: In this example, we will create/declare an iterator by specifying Integer type - which is base type of the List and then the methods next() and hasNext() will be called through Iterator object.

Example:

In this example, we will declare a List of integers, add some of the elements and print the elements by using hasNext() and next() methods.

Program:

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

Java List Programs »





Comments and Discussions!

Load comments ↻





Copyright © 2024 www.includehelp.com. All rights reserved.