![]() |
VOOZH | about |
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:
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:
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
TreeSet: 10, 39, 61, 87,
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
TreeSet: 10, 39, 61, 87,
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
TreeSet without Comma: 10 39 61 87 TreeSet with Comma: 10, 39, 61, 87