Fetch elements of Java TreeSet using Iteration

Java 8Object Oriented ProgrammingProgramming

Use Iterator class to fetch elements of TreeSet.

Create a TreeSet and add elements to it

TreeSet set = new TreeSet();
set.add("13");
set.add("11");
set.add("12");
set.add("16");
set.add("19");
set.add("23");
set.add("21");
set.add("20");
set.add("30");

Now, to display the elements, use Iterator class

Iterator<String> i = set.iterator();
while(i.hasNext()){
   System.out.println(i.next());
}

The following is an example that fetch elements of TreeSet using Iteration

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> set = new TreeSet<String>();
      set.add("13");
      set.add("11");
      set.add("12");
      set.add("16");
      set.add("19");
      set.add("23");
      set.add("21");
      set.add("20");
      set.add("30");
      System.out.println("TreeSet elements ...");
      Iterator<String> i = set.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
   }
}

Output

TreeSet elements ...
11
12
13
16
19
20
21
23
30
raja
Published on 18-Jan-2019 09:36:36
Advertisements