Copy all elements in Java TreeSet to an Object Array

Java 8Object Oriented ProgrammingProgramming

Create a TreeSet and add elements −

TreeSet<String> tSet = new TreeSet<String>();
tSet.add("TV");
tSet.add("Radio");
tSet.add("Internet");

Now, let us copy it to object array −

Object[] arr = tSet.toArray();
for (Object ob: arr) {
   System.out.println(ob);
}

The following is an example to copy all elements in TreeSet to an Object Array −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> tSet = new TreeSet<String>();
      tSet.add("TV");
      tSet.add("Radio");
      tSet.add("Internet");
      System.out.println("TreeSet elements = "+tSet);
      Object[] arr = tSet.toArray();
      for (Object ob: arr) {
         System.out.println(ob);
      }
   }
}

Output

TreeSet elements = [Internet, Radio, TV]
Internet
Radio
TV
raja
Published on 11-Jan-2019 06:21:18
Advertisements