Get the element ordered first in Java TreeSet

Java 8Object Oriented ProgrammingProgramming

To get the element ordered first i.e. the first element in TreeSet, use the first() method.

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, get the first element −

set.first()

The following is an example to get the element ordered first in TreeSet −

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("Element order first = "+set.first());
   }
}

Output

TreeSet elements (Sorted)...
19
27
45
57
65
89
Element ordered first = 19
raja
Published on 11-Jan-2019 07:03:55
Advertisements