Get the element ordered last in Java TreeSet

Java 8Object Oriented ProgrammingProgramming

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
raja
Published on 17-Jan-2019 17:54:53
Advertisements