How to Loop Over TreeSet in Java?
Last Updated :
05 Mar, 2024
TreeSet is one of the most important implementations of the SortedSet interface in Java that uses a Tree for storage. The ordering of the elements is maintained by a set using their natural ordering whether or not an explicit comparator is provided. This must be consistent with equals if it is to correctly implement the Set interface.Â
Now the task is to explore out how many ways are there in order to loop over TreeSet. As we all know TreeSet provides an implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like a simple set with the exception that it stores elements in a sorted format.
Following are some traits associated with TreeSet are as follows:
- TreeSet uses a Tree data structure for storage.
- Objects are stored in sorted, ascending order. But we can iterate in descending order using the method TreeSet.descendingIterator().
- Access and retrieval times are very fast which make TreeSet an excellent choice for the storage of large volume of data in a sorted format.
- TreeSet doesn’t use hashCode() and equals() methods to compare it’s elements. It uses compare() (or compareTo()) method to determine the equality of two elements.
Methods:
Below we  have listed various ways to iterate over the TreeSet in java which we are going to discuss further and will provide a clean java program for each of the following methods as follows:
- Using Enhanced For loop
- Using Iterator
- Using streams (from Java8 onwards)
Method 1: Using Enhanced For loop
Enhanced For loop can be used to loop over the TreeSet in the below manner.
Syntax:Â
for (Integer value : ts)
{
System.out.print(value);
}
ExampleÂ
Java
import java.util.Iterator;
import java.util.TreeSet;
public class GFG {
public static void main(String[] args)
{
TreeSet<Integer> ts = new TreeSet<Integer>();
ts.add( 10 );
ts.add( 61 );
ts.add( 87 );
ts.add( 39 );
System.out.print( "TreeSet: " );
for (Integer value : ts)
System.out.print(value + ", " );
System.out.println();
}
}
|
Output
TreeSet: 10, 39, 61, 87,
Method 2: Using Iterator
Iterator can be created over the TreeSet objects. Hence this iterator can be used to traverse or loop through the TreeSet.
Syntax:Â
Iterator iterator = ts.iterator();
while (iterator.hasNext())
{
System.out.print(iterator.next());
}
Example
Java
import java.util.Iterator;
import java.util.TreeSet;
public class GFG {
public static void main(String[] args)
{
TreeSet<Integer> ts = new TreeSet<Integer>();
ts.add( 10 );
ts.add( 61 );
ts.add( 87 );
ts.add( 39 );
Iterator<Integer> iterator = ts.iterator();
System.out.print( "TreeSet: " );
while (iterator.hasNext())
System.out.print(iterator.next() + ", " );
System.out.println();
}
}
|
Output
TreeSet: 10, 39, 61, 87,
Method 3: Using Java 8 forEach / stream:Â
Java 8 forEach / stream can be used to loop over the TreeSet in the below manner.
Syntax:
Tree_Set.forEach(iterator -> System.out.print(i + " "));
// Using forEachÂ
Tree_Set.stream().map(iterator -> String.valueOf(i)).collect(Collectors.joining(", "))
// Using streamÂ
Example
Java
import java.util.Arrays;
import java.util.Iterator;
import java.util.TreeSet;
import java.util.stream.Collectors;
public class GFG {
public static void main(String[] args)
{
TreeSet<Integer> ts = new TreeSet<Integer>();
ts.addAll(Arrays.asList( 10 , 61 , 87 , 39 ));
System.out.print( "TreeSet without Comma: " );
ts.forEach(i -> System.out.print(i + " " ));
System.out.println();
System.out.print( "TreeSet with Comma: " );
System.out.print(
ts.stream()
.map(i -> String.valueOf(i))
.collect(Collectors.joining( ", " )));
}
}
|
Output
TreeSet without Comma: 10 39 61 87
TreeSet with Comma: 10, 39, 61, 87
Share your thoughts in the comments
Please Login to comment...