How to loop over 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 than TreeSet sorts elements in their natural order e.g. String elements are sorted in alphabetic order and Integer elements are sorted in numeric order. When you iterate over a TreeSet the iterator follows this order.
Read more »