TreeSet
TreeSet Iterator example
In this example we shall show you how to get a TreeSet Iterator. To get a TreeSet Iterator one should perform the following steps:
- Create a new TreeSet.
- Populate the set with elements, with
add(E e)
API method of TreeSet. - Obtain an Iterator of the set, with
iterator(
) API method of TreeSet. It is an iterator over the elements in this set in ascending order. - Iterate over the set’s elements, with
hasNext()
,next()
API methods of Iterator, to get the TreeSet’s elements,
as described in the code snippet below.
package com.javacodegeeks.snippets.core; import java.util.TreeSet; import java.util.Iterator; public class TreeSetIteratorExample { public static void main(String[] args) { // Create a TreeSet and populate it with elements TreeSet treeSet = new TreeSet(); treeSet.add("element_1"); treeSet.add("element_2"); treeSet.add("element_3"); // To get the Iterator use the iterator() operation Iterator it = treeSet.iterator(); System.out.println("Elements in TreeSet :"); while(it.hasNext()) System.out.println(it.next()); } }
Output:
Elements in TreeSet :
element_1
element_2
element_3
This was an example of how to get a TreeSet Iterator in Java.