In the previous article, we have discussed about Java LinkedList lastIndexOf() Method with Examples
In this article we are going to see the use of Java LinkedList iterator() method along with suitable examples.
Java LinkedList iterator() Method with Examples
This java.util.LinkedList.iterator()
method is used to get an iterator to retrieve each element of the LinkedList in a proper order.
Syntax:
LinkedListName.iterator()
Where,
LinkedListName
refers to the name of your LinkedList.
Let’s see different examples to understand it more clearly.
Example-1: Java LinkedList iterator() Method – Example with String Type LinkedList
Approach:
- Create a new LinkedList of type String.
- Add string elements into the LinkedList using the add() method.
- Display the LinkedList elements.
- Create a variable of Iterator and store the iterator returned by iterator() method.
- Use a while loop through LinkedList till it has all elements.
- Inside
iterator()
method there is some inbuild methods likehasNext()
to check next element exists or not andnext()
to access the next element. - Print the LinkedList.
Program:
import java.util.*; public class Main { public static void main(String[] args) { // Create an LinkedList of string datatype LinkedList<String> l1 = new LinkedList<String>(); // Adding some elements to the LinkedList l1.add("vivo"); l1.add("htc"); l1.add("samsung"); l1.add("realme"); l1.add("nokia"); // Prints the LinkedList elements System.out.println("The elements in the LinkedList are: "+l1); // Create an object of Iterator Iterator<String> iterate = l1.iterator(); System.out.print("LinkedList: "); // loop through LinkedList till it has all elements while(iterate.hasNext()) { // Use methods of Iterator to access elements System.out.print(iterate.next()); System.out.print(" "); } } }
Output: The elements in the LinkedList are: [vivo, htc, samsung, realme, nokia] LinkedList: vivo htc samsung realme nokia
Don’t miss the chance of Java programs examples with output pdf free download as it is very essential for all beginners to experienced programmers for cracking the interviews.
Related Java Programs: