Get the last element from a Sorted Set in Java


To create a Sorted Set, firstly create a Set −

Set<Integer> s = new HashSet<Integer>();

Add elements to the above set −

int a[] = {77, 23, 4, 66, 99, 112, 45, 56, 39, 89};
Set<Integer> s = new HashSet<Integer>();
try {
   for(int i = 0; i < 5; i++) {
   s.add(a[i]);
}

After that, use TreeSet class to sort −

TreeSet sorted = new TreeSet<Integer>(s);

Get the last element, using the last() method −

System.out.println("
Last element of the sorted set = "+ (Integer)sorted.last());

The following is the code to get the last element from a Sorted Set in Java −

Example

 Live Demo

import java.util.*;
public class Demo {
   public static void main(String args[]) {
      int a[] = {77, 23, 4, 66, 99, 112, 45, 56, 39, 89};
      Set<Integer> s = new HashSet<Integer>();
      try {
         for(int i = 0; i < 5; i++) {
            s.add(a[i]);
         }
         System.out.println(s);
         TreeSet sorted = new TreeSet<Integer>(s);
         System.out.println("Sorted list = ");
         System.out.println(sorted);
         System.out.println("
Last element of the sorted set = "+ (Integer)sorted.last());       }       catch(Exception e) {}    } }

Output

[66, 99, 4, 23, 77]
Sorted list =
[4, 23, 66, 77, 99]
Last element of the sorted set = 99

Samual Sam
Samual Sam

Learning faster. Every day.

Updated on: 25-Jun-2020

2K+ Views

Kickstart Your Career

Get certified by completing the course

Get Started
Advertisements