What is the Deque.iterator() method in Java?

In this shot, we will discuss the Deque.iterator() method in Java.

The Deque.iterator() method is present in the Deque interface inside the java.util package.

Deque.iterator() returns the iterator over the deque elements in the sequence they are present in.

Syntax

Iterator iterator()

Parameters

The Deque.iterator() method doesn’t take any parameters.

Return value

  • Iterator: The iterator over the deque elements in the sequence they are present in.

Code

Let’s take a look at the following code snippet.

import java.util.*;
class Main
{
public static void main(String[] args)
{
Deque<Integer> d = new LinkedList<Integer>();
d.add(2);
d.add(28);
d.add(6);
d.add(80);
d.add(21);
d.add(7);
d.add(15);
Iterator i = d.iterator();
System.out.print("The iterator values of deque are: ");
while (i.hasNext())
{
System.out.print(i.next()+" ");
}
System.out.println();
}
}

Explanation

  • Line 1: We import the required package.
  • Line 2: We make a Main class.
  • Line 4: We make a main function.
  • Line 6: We declare a deque that consists of Integer type elements.
  • Lines 8 to 14: We use the Deque.add() method to insert the elements in the deque.
  • Line 16: We declare an iterator for deque.
  • Lines 18 to 21: We use a while loop to check the presence of the next element in the deque with the Iterator.hasNext() method. We then display the value of the iterator over each element.

Free Resources