- Data Structure
- Networking
- RDBMS
- Operating System
- Java
- MS Excel
- iOS
- HTML
- CSS
- Android
- Python
- C Programming
- C++
- C#
- MongoDB
- MySQL
- Javascript
- PHP
- Physics
- Chemistry
- Biology
- Mathematics
- English
- Economics
- Psychology
- Social Studies
- Fashion Studies
- Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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 TreeSetextends 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
Advertisements