Home > Java > javaTutorial > body text

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

WBOY
Release: 2023-09-05 09:37:02
forward
1004 people have browsed it

在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
Copy after login

We can iterate in two waysTreeSet

Using iterators

We can iterateTreeSet < /strong>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>);
      }
   }
}
Copy after login

Output

Adithya
Chaitanya
Jai
Ramesh
Vamsi
Copy after login

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);
      }
   }
}
Copy after login

Output

Australia<strong>
</strong>England
India
South Africa
West Indies
Copy after login

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!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!