Given a TreeSet in Java, the task is to loop over this TreeSet.
TreeSet provides an implementation of the SortedSet Interface and SortedSet extends Set Interface. It behaves like simple set with the exception that it stores elements in sorted format.
Following are the features of TreeSet.
- TreeSet uses tree data structure for storage.
- Objects are stored in sorted, ascending order. But we can iterate in descending order using method TreeSet.descendingIterator().
- Access and retrieval times are very fast which make TreeSet an excellent choice for storage of large volume of data in 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.
Below are the two methods to loop over the TreeSet in Java:
- 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());Program:
// Java program to loop over TreeSetimportjava.util.Iterator;importjava.util.TreeSet;publicclassTreeSetExample {publicstaticvoidmain(String[] args){TreeSet<Integer>ts =newTreeSet<Integer>();ts.add(10);ts.add(61);ts.add(87);ts.add(39);// Create an Iterator over the TreeSetIterator<Integer> iterator = ts.iterator();// Loop over the TreeSet values// and print the valuesSystem.out.print("TreeSet: ");while(iterator.hasNext())System.out.print(iterator.next()+", ");System.out.println();}}Output:TreeSet: 10, 39, 61, 87,
- 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); }Program:
// Java program to loop over TreeSetimportjava.util.Iterator;importjava.util.TreeSet;publicclassTreeSetExample {publicstaticvoidmain(String[] args){TreeSet<Integer>ts =newTreeSet<Integer>();ts.add(10);ts.add(61);ts.add(87);ts.add(39);// Loop over the TreeSet values// and print the valuesSystem.out.print("TreeSet: ");for(Integer value : ts)System.out.print(value+", ");System.out.println();}}Output:TreeSet: 10, 39, 61, 87,
- Using Java 8 forEach / stream: Java 8 forEach / stream can be used to loop over the TreeSet in the below manner.
Syntax:
// Using forEach
Tree_Set.forEach(iterator -> System.out.print(i + ” “));// Using stream
Tree_Set.stream().map(iterator -> String.valueOf(i)).collect(Collectors.joining(“, “))Program:
// Java program to loop over TreeSet// Needful librariesimportjava.util.Iterator;importjava.util.TreeSet;importjava.util.Arrays;importjava.util.stream.Collectors;publicclassTreeSetExample {publicstaticvoidmain(String[] args){// TreeSet objectTreeSet<Integer>ts =newTreeSet<Integer>();// Adding elements to the TreeSetts.addAll(Arrays.asList(10,61,87,39));// Loop over the TreeSet & print valuesSystem.out.print("TreeSet without Comma: ");// Iterating through the TreeSet// using forEachts.forEach(i -> System.out.print(i +" "));System.out.println();// Loop over the TreeSet & print valuesSystem.out.print("TreeSet with Comma: ");// Iterating through the TreeSet// using streamSystem.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
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.


