Home >Java >javaTutorial >How many ways are there to iterate over a TreeSet in Java?

How many ways are there to iterate over a TreeSet in Java?

WBOY
WBOYforward
2023-09-05 09:37:021060browse

在Java中,有几种方法可以迭代TreeSet?

Treeset is a subclass of the AbstractSet class and implements the NavigableSet interface. By default, Treeset provides ascending output and will use the Comparable interface to sort the set elements. In Treeset, we can add elements of the same type, otherwise ClassCastException may be generated, because by default TreeSet uses the Comparable interface .

Syntax

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

We can iterate in two waysTreeSet

Using iterators

We can iterateTreeSet UseIteratorInterface

Example

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

Output

Adithya
Chaitanya
Jai
Ramesh
Vamsi

Use for-each loop

We can usefor-each IterationElements of TreeSet>Loop

Example

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

Output

Australia<strong>
</strong>England
India
South Africa
West Indies

The above is the detailed content of How many ways are there to iterate over a TreeSet in Java?. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:tutorialspoint.com. If there is any infringement, please contact admin@php.cn delete