Iterating Java LinkedList in descending order

In this tutorial we will learn how to iterate a LinkedList in descending order. we will use descendingIterator() method of java.util.LinkedList class to perform this.

Signature

public Iterator<E> descendingIterator() 

Returns an iterator over the elements in this deque in reverse sequential order.

Example

The following example shows the usage of java.util.descendingIterator() method.

import java.util.Iterator;
import java.util.LinkedList;

public class DescendingIteratorMethodLinkedListExample {
	public static void main(String args[])
	{
		// create an empty LinkedList
		LinkedList list1 = new LinkedList();
		
		// use add() method to add elements to the LinkedList
		list1.add("Element1");
		list1.add("Element2");
		list1.add("Element3");
		
		//Printing the elements of the LinkedList in actual order
		System.out.println("**Before Reversing**");
		Iterator iterator1 = list1.iterator();
		while(iterator1.hasNext())
		{
			System.out.println(iterator1.next());
		}
		
		//Iterating the LinkedList in the descending order
		System.out.println("After Reversing");
		Iterator iterator2 = list1.descendingIterator();
		while(iterator2.hasNext())
		{
			System.out.println(iterator2.next());
		}
		
	}
}

Output

**Before Reversing**
Element1
Element2
Element3
After Reversing
Element3
Element2
Element1

Leave a Reply

Your email address will not be published. Required fields are marked *