How many ways to iterate a TreeSet in Java?

JavaObject Oriented ProgrammingProgramming

A Treeset is a subclass of AbstractSet class and implements NavigableSet Interface. By Default, a Treeset gives an ascending order of output and it will use a Comparable interface for sorting the set elements. Inside a Treeset, we can add the same type of elements otherwise it can generate a ClassCastException because by default TreeSet uses a Comparable interface.

Syntax

public class TreeSet<E> extends AbstractSet<E> implements NavigableSet<E>, Cloneable, Serializable

We can iterate a TreeSet in two ways

Using Iterator

We can iterate the elements of a TreeSet using Iterator interface

Example

import java.util.*;
public class IteratingTreeSetTest {
   public static void main(String[] args) {
      Set<String> treeSetObj = new TreeSet<String>();
      treeSetObj.add("Ramesh");
      treeSetObj.add("Adithya");
      treeSetObj.add("Jai");
      treeSetObj.add("Vamsi");
      treeSetObj.add("Chaitanya");
      Iterator<String> it = treeSetObj.iterator(); // Iterator interface
      while (it.hasNext()) {
         System.out.println(it.next());
      }
   }
}

Output

Adithya
Chaitanya
Jai
Ramesh
Vamsi

Using a for-each loop

We can iterate the elements of a TreeSet using the for-each loop

Example

import java.util.*;
public class IteratingTreeSetForEachTest {
   public static void main(String[] args) {
      Set<String> treeSetObj = new TreeSet<String>();
      treeSetObj.add("India");
      treeSetObj.add("Australia");
      treeSetObj.add("West Indies");
      treeSetObj.add("South Africa");
      treeSetObj.add("England");
      for(String str : treeSetObj) { // for-each loop
         System.out.println(str);
      }
   }
}

Output

Australia
England
India
South Africa
West Indies
raja
Published on 30-Aug-2019 13:04:45
Advertisements