Syntax error Get the element ordered first in Java TreeSet

Get the element ordered first in Java TreeSet



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
Updated on: 2019-07-30T22:30:24+05:30

155 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements