Traverse TreeSet elements in descending order in java

Java 8Object Oriented ProgrammingProgramming

Create TreeSet and add elements to it

TreeSet<String> tSet = new TreeSet<String>();
tSet.add("P");
tSet.add("Q");
tSet.add("R");
tSet.add("S");

Now, let us traverse elements in descending order

Iterator j = tSet.descendingIterator();
while(j.hasNext()) {
   System.out.println(j.next());
}

The following is an example to traverse TreeSet elements in descending order

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]){
      TreeSet<String> tSet = new TreeSet<String>();
      tSet.add("P");
      tSet.add("Q");
      tSet.add("R");
      tSet.add("S");
      System.out.println("TreeSet elements...");
      Iterator<String> i = tSet.iterator();
      while(i.hasNext()){
         System.out.println(i.next());
      }
      System.out.println("TreeSet elements in Descending order...");
      Iterator<String> j = tSet.descendingIterator();
      while(j.hasNext()) {
         System.out.println(j.next());
      }
   }
}

Output

The output is as follows

TreeSet elements...
P
Q
R
S
TreeSet elements in Descending order...
S
R
Q
P
raja
Published on 17-Jan-2019 14:14:33
Advertisements