Iterate TreeSet in Java

In this tutorial, we will learn how to Iterate TreeSet in Java.

TreeSet in Java extends AbstractSet and implements the NavigableSet interface. It creates a collection that uses a tree for storage. The objects are stored in sorted, ascending order. Access and retrieval times are quite fast, which makes TreeSet an excellent choice when storing large amounts of sorted information that must be found quickly. TreeSet is similar to HashSet, the difference is that TreeSet sorts the elements in ascending order and doesn’t allow null elements.

There are many ways to iterate TreeSet in Java. We can iterate TreeSet using Iterator or for loop or while loop etc. If we want to iterate using Iterator, then we need to get Iterator by calling the method iterator() on TreeSet . Let’s see this with an example.

Example:

Output:

In the above program, we have iterated TreeSet using an Iterator and for loop.

Related posts

Leave a Comment