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
- 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);
- }
- }
- }
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
- 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());
- }
- }
- }
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