Create a TreeSet in Java

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");

Iterate through the elements −

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

The following is an example to create a TreeSet −

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");
      Iterator<String> i = tSet.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
   }
}

Output

Internet
Radio
TV
raja
Published on 11-Jan-2019 10:49:26
Advertisements