Saturday, September 30, 2023

How to loop over a TreeSet in Java with Example

In our earlier articles, we have learned how to loop over ArrayList in Java and you can use the same logic to loop over a TreeSet. You can use both, enhanced for loop and Iterator to traverse over TreeSet in Java. Though worth noting is that Iterator returned by the iterator() method of TreeSet returns elements in the sorted order which is imposed by the Comparator you have provided to TreeSet at the time of instantiation. By default, if you don't provide any custom Comparator then TreeSet sorts elements in their natural order like String elements are sorted in alphabetical order and Integer elements are sorted in numeric order. When you iterate over a TreeSet the iterator follows this order.

You can also use the enhanced for loop, which also internally uses the Iterator and traverse the TreeSet in the same order, but you cannot remove an element there. On the other hand, Iterator allows you to remove elements while iterating over TreeSet. In this article, you will find examples of both approaches.


For those who are new to TreeSet, A TreeSet is a sorted collection in Java. You insert an element in any order but when you iterate through the collection, the values are automatically presented in the sorted order. The sorting is accomplished by a tree data structure. 

The current implementation of java.util.TreeSet uses a Red-Black tree. For a detailed description of red-black trees, see a good algorithm book e.g. Introduction to Algorithms By Thomas Cormen, Charles Leiserson, Ronald Rivest, and Clifford Stein. Every time an element is added to a tree, it is placed into its proper sorting position. Therefore, the iterator always visits the elements in sorted order.





Iterating over TreeSet using Iterator Example

You can follow 3 steps to start iterating over TreeSet using Iterator, remember this is going from first to the last element in the sorted order.

1) get the Iterator by calling the iterator() method
2) Use a for or while loop with hasNext()
3) Call the next() method

Iterator<String> itr = treeSetOfScrips.iterator();
while (itr.hasNext()) {
   System.out.println(itr.next());
}

You can also remove the current element by calling the remove() method of Iterator, don't use the remove() method provided by the java.util.Collection interface because that will result in ConcurrentModificationException as shown here.


Looping over TreeSet using enhanced for loop of Java 5

Here is the sample code to loop over TreeSet using advanced for loop, Remember you cannot remove elements when you are using enhanced for loop of JDK 1.5 release.

for (String stock : treeSetOfScrips) {
   System.out.println(stock);
}

There is also a third way to iterate over TreeSet in Java but that is only available from JDK 8 onwards. You can use the forEach() method to iterate over any Collection including TreeSet in Java 8 because this method comes from java.util.Iterable interface.

Here is a nice slide showing how to loop over TreeSet using both iterator and enhanced for loop of JDK 5 in Java program:

How to loop over TreeSet in Java with Example


Java Program to traverse over TreeSet in Java

Here is our complete Java program which shows step by step guide to iterate over TreeSet in Java. This program contains both examples i.e. iterating over TreeSet using Iterator and using enhanced for loop of Java 5.

import java.util.TreeSet;
import java.util.Iterator;
import java.util.Set;

public class TreeSetLoopingDemo{

public static void main(String args[]) {

// Creating and initializing an TreeSet for iteration
Set<String> treeSetOfScrips = new TreeSet<>();
treeSetOfScrips.add("MSFT");
treeSetOfScrips.add("INFY");
treeSetOfScrips.add("BABA");
treeSetOfScrips.add("GOOG");
treeSetOfScrips.add("AMZN");

System.out.println("TreeSet: " + treeSetOfScrips);

// Example 1 - iterating over TreeSet using Iterator
// Obtaining the Iterator
Iterator<String> itr = treeSetOfScrips.iterator();

// traversing over TreeSet
System.out.println("Traversing over TreeSet using Iterator");
while (itr.hasNext()) {
System.out.println(itr.next());
}

// Example 2 - looping over TreeSet using for loop
System.out.println("Looping over TreeSet using advanced for loop");
for (String stock : treeSetOfScrips) {
System.out.println(stock);
}
}
}

Output:
TreeSet: [AMZN, BABA, GOOG, INFY, MSFT]
Traversing over TreeSet using Iterator
AMZN
BABA
GOOG
INFY
MSFT
Looping over TreeSet using advanced for loop
AMZN
BABA
GOOG
INFY
MSFT

That's all about how to iterate over TreeSet in Java. You can use any of the approaches to loop over a TreeSet but the recommendation is to use Iterator particularly if you want to remove elements from TreeSet while iterating over it. You can use enhanced for loop for just accessing the elements like for printing contents of TreeSet. This approach is similar to Iterator but results in cleaner code.


If you are curious to learn more about TreeSet and Java Collection framework you can also check out the following articles:
  • 3 ways to loop over a Map in Java? (solution)
  • The difference between TreeSet and HashSet in Java? (answer)
  • How to traverse over a List in Java? (example)
  • 6 differences between LinkedHashSet and TreeSet in Java? (answer)
  • How to iterate over HashSet in Java? (solution)
  • The best way to iterate over each entry of HashMap in Java? (answer)

And lastly one question for you, what is difference between TreeSet and LinkedHashSet in Java? If you know let me know in comments as its a popular Java question and if you don't know see my earlier article difference between TreeSet, HashSet, and LinkedHashSet in Java

No comments:

Post a Comment

Feel free to comment, ask questions if you have any doubt.