Java TreeSet descendingIterator() Method

Beginner
5 min read
Updated: Nov 2026
3 examples
Java 6+

Definition

In Java, descendingIterator() returns an Iterator<E> that steps through the TreeSet in descending order—from the largest element down to the smallest.

It gives you reverse traversal directly on the tree without creating a second set. Note that you cannot write for (E x : set.descendingIterator()) directly because Iterator is not Iterable; loop with while (it.hasNext()) or use descendingSet() in a for-each loop.

An instance method of java.util.TreeSet (Java 6+ (added via NavigableSet in JDK 1.6)): a red-black tree NavigableSet backed by a TreeMap that keeps unique elements sorted in O(log n) time and is not thread-safe.

Syntax

Fetch a descending iterator and walk elements with a while loop.

Java
NavigableSet<Integer> versions = new TreeSet<>(Arrays.asList(1, 2, 3));
Iterator<Integer> it = versions.descendingIterator();
while (it.hasNext()) {
    System.out.println(it.next());   // 3, then 2, then 1
}
CallWhat it does
set.descendingIterator()Iterator running from last() down to first().
it.next()Returns the next smaller element.
it.remove()Safely deletes the current element during reverse traversal.
for (E x : set.descendingSet())For-each equivalent using the reversed view.

With a custom descending comparator, descendingIterator() reverses that comparator too, walking in ascending natural order.

Library declarations
Java
// java.util.TreeSet<E>  (since Java 6)
public Iterator<E> descendingIterator()

// Declared in NavigableSet<E>

Parameters

ParameterDescription
NonedescendingIterator() takes no parameters.

Return Value

Return ValueDescription
Iterator<E>A fail-fast iterator over elements from largest to smallest.

Compare with Similar Methods

Ways to walk or reverse a TreeSet:

MethodHow it differs
descendingSet()Returns an Iterable NavigableSet view usable in enhanced for loops.
iterator()Walks in ascending order (first() to last()).
pollLast()Pops elements highest-first while emptying the set.
ArrayDeque.descendingIterator()Iterates tail-to-head in insertion order rather than sorted order.

Java Examples

Example 1 — Print Release Years From Newest Down to Oldest

Walk sorted release years backward using descendingIterator() without allocating a reversed copy.

Java
import java.util.Arrays;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

public class TreeSetDescIterYears {
    public static void main(String[] args) {
        NavigableSet<Integer> years = new TreeSet<>(Arrays.asList(2019, 2023, 2021, 2026));
        Iterator<Integer> rev = years.descendingIterator();

        System.out.println("newest to oldest:");
        while (rev.hasNext()) {
            System.out.println("- " + rev.next());
        }
        System.out.println("original unchanged: " + years);
    }
}

How It Works

  1. Tree remains ascending. years stores 2019..2026 in natural order.
  2. Backward step order. descendingIterator() begins at 2026 and visits 2023, 2021, and 2019.
  3. Non-destructive walk. Printing years afterwards confirms all four years remain inside.

Example 2 — Remove Spike Readings Above 40 While Walking Backward

Use descendingIterator() and it.remove() to stop as soon as values drop at or below 40.

Java
import java.util.Arrays;
import java.util.Iterator;
import java.util.NavigableSet;
import java.util.TreeSet;

public class TreeSetDescIterPrune {
    public static void main(String[] args) {
        NavigableSet<Integer> temps = new TreeSet<>(Arrays.asList(22, 29, 41, 38, 47));
        Iterator<Integer> it = temps.descendingIterator();

        while (it.hasNext()) {
            int t = it.next();
            if (t > 40) {
                System.out.println("dropping spike: " + t);
                it.remove();
            } else {
                break;
            }
        }
        System.out.println("clean temps: " + temps);
    }
}

How It Works

  1. Start at the biggest values. Descending order puts 47 and 41 at the very beginning of the traversal.
  2. Safe removal + early exit. Once t <= 40 (at 38), break stops immediately without scanning 29 or 22.
  3. Both spikes removed cleanly. clean temps holds only 22, 29, and 38.

Example 3 — ConcurrentModificationException and Exhausted Iterator Behavior

Trigger fail-fast detection after removing from the set directly, then catch NoSuchElementException on an exhausted iterator.

Java
import java.util.Arrays;
import java.util.ConcurrentModificationException;
import java.util.Iterator;
import java.util.NoSuchElementException;
import java.util.TreeSet;

public class TreeSetDescIterErrors {
    public static void main(String[] args) {
        TreeSet<String> logs = new TreeSet<>(Arrays.asList("L1", "L2", "L3"));
        Iterator<String> it = logs.descendingIterator();
        System.out.println("latest: " + it.next());

        logs.remove("L1");
        try {
            it.next();
        } catch (ConcurrentModificationException e) {
            System.out.println("direct remove: " + e.getClass().getSimpleName());
        }

        Iterator<String> tail = logs.descendingIterator();
        while (tail.hasNext()) {
            tail.next();
        }
        try {
            tail.next();
        } catch (NoSuchElementException e) {
            System.out.println("past end: " + e.getClass().getSimpleName());
        }
    }
}

How It Works

  1. Structural edit invalidates cursor. Removing "L1" directly on logs bumps the modification counter, breaking it.next().
  2. Exhausted cursor throws at end. Draining tail leaves nothing left, so an extra next() raises NoSuchElementException.
  3. Guard with hasNext(). Always pair descendingIterator() with a hasNext() condition.

Frequently Asked Questions

It returns an Iterator that traverses the TreeSet elements in reverse order, from largest to smallest.
Not directly, because Iterator does not implement Iterable. Use while (it.hasNext()) or loop over set.descendingSet() in a for-each loop instead.
Yes. Calling it.remove() after it.next() safely deletes the current element without throwing ConcurrentModificationException.
descendingIterator() returns a lightweight single-pass Iterator; descendingSet() returns a full live NavigableSet view.
Java 6 (JDK 1.6), as part of the NavigableSet interface.

Next: descendingSet()

Get a live reversed view of the set from largest to smallest.

descendingSet() tutorial →

About the author

Mari Selvan M P
Mari Selvan M P 🔗

Developer, cloud engineer, and technical writer

  • Experience 12 years building web and cloud systems
  • Focus Full Stack Development, AWS, and Developer Education

I write practical tutorials so students and working developers can learn by doing—from databases and APIs to deployment on AWS.

14 people found this page helpful