Syntax error Get the element ordered last in Java TreeSet

Get the element ordered last in Java TreeSet



To get the element ordered last i.e. the last element in TreeSet, use the last() 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 last element

set.last()

The following is an example to get the element ordered last in TreeSt

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

Output

TreeSet elements (Sorted)...
19
27
45
57
65
89
Element ordered last = 89
Updated on: 2019-07-30T22:30:24+05:30

213 Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements