How many ways to iterate a TreeSet in Java?


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 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

Updated on: 29-Nov-2023

662 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements