Sort items in a Java TreeSet

Java 8Object Oriented ProgrammingProgramming

First, create a TreeSet and add elements to it −

TreeSet<String> set = new TreeSet<String>();
set.add("65");
set.add("45");
set.add("19");
set.add("27");
set.add("89");
set.add("57");

Now, sort it in ascending order, which is the default −

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

If you want to sort in descending order, then use the descendingIterator() method −

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

The following is an example to sort items in a TreeSet in ascending and descending order −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> set = new TreeSet<String>();
      set.add("65");
      set.add("45");
      set.add("19");
      set.add("27");
      set.add("89");
      set.add("57");
      System.out.println("TreeSet elements (Sorted)...");
      Iterator<String> i = set.iterator();
      while(i.hasNext()) {
         System.out.println(i.next());
      }
      System.out.println("\nTreeSet elements (Sorted) in Descending order...");
      Iterator<String> j = set.descendingIterator();
      while(j.hasNext()) {
         System.out.println(j.next());
      }
   }
}

Output

TreeSet elements (Sorted)...
19
27
45
57
65
89

TreeSet elements (Sorted) in Descending order...
89
65
57
45
27
19
raja
Published on 11-Jan-2019 07:02:05
Advertisements