TreeSet with looping

In this article, we will see how to loop TreeSet in java

Its very much common requirement to iterate or loop through TreeSet in java applications

There are mainly 2 ways to loop through Treeset in java


1) Enhanced For loop
2) Iterator

Let’s see each of these ways with an example

1) Enhanced For loop

  1. import java.util.*;
  2.  
  3. public class TreeSetEnhancedForLoop {
  4. public static void main(String[] args) {
  5. TreeSet<Integer> ts= new TreeSet<Integer>();
  6. ts.add(14);
  7. ts.add(7);
  8. ts.add(21);
  9. ts.add(28);
  10. System.out.println(“Enhanced For Loop”);
  11. for (Integer element : ts) {
  12. System.out.println(element);
  13.      }
  14.    }
  15. }
import java.util.*;

public class TreeSetEnhancedForLoop {
public static void main(String[] args) {
TreeSet<Integer> ts= new TreeSet<Integer>();
ts.add(14);
ts.add(7);
ts.add(21);
ts.add(28);
System.out.println(“Enhanced For Loop”);
for (Integer element : ts) {
System.out.println(element);
     }
   }
}
Note : In the above example, we have used advanced/enhanced for loop to iterate TreeSet 
            and their elements are in sorted order

2) Iterator
  1. import java.util.*;
  2.  
  3. public class TreeSetIterator {
  4. public static void main(String[] args) {
  5. TreeSet<Integer> ts= new TreeSet<Integer>();
  6. ts.add(14);
  7. ts.add(7);
  8. ts.add(21);
  9. ts.add(28);
  10. System.out.println(While with iterator”);
  11. Iterator itr = ts.iterator();
  12. while (itr.hasNext()) {
  13. System.out.println(itr.next());
  14. }
  15. }
  16. }
import java.util.*;

public class TreeSetIterator {
public static void main(String[] args) {
TreeSet<Integer> ts= new TreeSet<Integer>();
ts.add(14);
ts.add(7);
ts.add(21);
ts.add(28);
System.out.println(“While with iterator”);
Iterator itr = ts.iterator();
while (itr.hasNext()) {
System.out.println(itr.next());
}
}
}
Note : We can’t access TreeSet elements using index in the way we access in Arraylist

About the Author

Founder of javainsimpleway.com
I love Java and open source technologies and very much passionate about software development.
I like to share my knowledge with others especially on technology 🙂
I have given all the examples as simple as possible to understand for the beginners.
All the code posted on my blog is developed,compiled and tested in my development environment.
If you find any mistakes or bugs, Please drop an email to kb.knowledge.sharing@gmail.com

Connect with me on Facebook for more updates

Share this article on