VOOZH about

URL: https://www.geeksforgeeks.org/java/how-to-loop-over-treeset-in-java/

⇱ How to Loop Over TreeSet in Java? - GeeksforGeeks


  • Courses
  • Tutorials
  • Interview Prep

How to Loop Over TreeSet in Java?

Last Updated : 11 Jul, 2025

TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface

Now the task is to explore out how many ways are there in order to loop over TreeSet. As we all know TreeSet provides an implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like a simple set with the exception that it stores elements in a sorted format.

👁 Collections-in-Java

Following are some traits associated with TreeSet are as follows:

  • TreeSet uses a Tree data structure for storage.
  • Objects are stored in sorted, ascending order. But we can iterate in descending order using the method TreeSet.descendingIterator().
  • Access and retrieval times are very fast which make TreeSet an excellent choice for the storage of large volume of data in a sorted format.
  • TreeSet doesn’t use hashCode() and equals() methods to compare it’s elements. It uses compare() (or compareTo()) method to determine the equality of two elements.

Methods:

Below we  have listed various ways to iterate over the TreeSet in java which we are going to discuss further and will provide a clean java program for each of the following methods as follows:

  1. Using Enhanced For loop
  2. Using Iterator
  3. Using streams (from Java8 onwards)


Method 1: Using Enhanced For loop

Enhanced For loop can be used to loop over the TreeSet in the below manner.

Syntax:

for (Integer value : ts)
{
System.out.print(value);
}

Example


Output
TreeSet: 10, 39, 61, 87, 


Method 2: Using Iterator

Iterator can be created over the TreeSet objects. Hence this iterator can be used to traverse or loop through the TreeSet.

Syntax:

Iterator iterator = ts.iterator();

while (iterator.hasNext())
{
System.out.print(iterator.next());
}

Example


Output
TreeSet: 10, 39, 61, 87, 


Method 3: Using Java 8 forEach / stream

Java 8 forEach / stream can be used to loop over the TreeSet in the below manner.

Syntax:

Tree_Set.forEach(iterator -> System.out.print(i + " "));
// Using forEach 

Tree_Set.stream().map(iterator -> String.valueOf(i)).collect(Collectors.joining(", "))
// Using stream 

Example


Output
TreeSet without Comma: 10 39 61 87 
TreeSet with Comma: 10, 39, 61, 87
Comment