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:
Output