In this section, we will learn what the Deque descendingIterator() and iterator() methods are and how to use them in Java.
What is Java Deque descendingIterator() Method?
The Java Deque descendingIterator() method is used to return an iterator object by which we can iterate through the elements of a Deque.
This method returns the element of the Deque in a reverse order (starting from the last element to the first element).
Note: check the Iterator section if you’re not familiar with this interface.
Java descendingIterator() Method Syntax:
Iterator<E> descendingIterator()
descendingIterator() Method Parameters:
The method does not take an argument.
descendingIterator() Method Return Value:
The return value of this method is an iterator object that implemented the Iterator interface.
descendingIterator() Method Exceptions:
The method does not throw an exception.
Example: using Deque descendingIterator() method
import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; class Main{ public static void main(String[] args) { Deque<Integer> deque = new ArrayDeque<>(); deque.add(30); deque.add(20); deque.add(10); deque.add(40); deque.add(50); Iterator<Integer> iterate =deque.descendingIterator(); while (iterate.hasNext()){ System.out.println(iterate.next()); } } }
Output:
50 40 10 20 30
What is Java Deque iterator() Method?
The Java Deque iterator() method is used to get an Iterator object from a Deque by which we can iterate through the elements of the Deque.
The returned iterator object iterates from the first element of the Deque object to the last one (from head to tail).
Note: if you’re not familiar with the Iterator interface, please check the related section.
Java iterator() Method Syntax:
Iterator<E> iterator()
iterator() Method Parameters:
The method does not take an argument.
iterator() Method Return Value:
The return value of this method is an object that implemented the Iterator interface.
iterator() Method Exceptions:
The method does not throw an exception.
Example: using Deque iterator() method
import java.util.ArrayDeque; import java.util.Deque; import java.util.Iterator; class Main{ public static void main(String[] args) { Deque<Integer> deque = new ArrayDeque<>(); deque.add(30); deque.add(20); deque.add(10); deque.add(40); deque.add(50); Iterator<Integer> iterate =deque.iterator(); while (iterate.hasNext()){ System.out.println(iterate.next()); } } }
Output:
30 20 10 40 50