Home » Java programs » Java list programs

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.


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.


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());
		System.out.println ("Total traversed elements are: "+count);


List elements are...
Total traversed elements are: 5

Comments and Discussions

Ad: Are you a blogger? Join our Blogging forum.

Languages: » C » C++ » C++ STL » Java » Data Structure » C#.Net » Android » Kotlin » SQL
Web Technologies: » PHP » Python » JavaScript » CSS » Ajax » Node.js » Web programming/HTML
Solved programs: » C » C++ » DS » Java » C#
Aptitude que. & ans.: » C » C++ » Java » DBMS
Interview que. & ans.: » C » Embedded C » Java » SEO » HR
CS Subjects: » CS Basics » O.S. » Networks » DBMS » Embedded Systems » Cloud Computing » Machine learning » CS Organizations » Linux » DOS
More: » Articles » Puzzles » News/Updates

© https://www.includehelp.com some rights reserved.