- Trending Categories
Data Structure
Networking
RDBMS
Operating System
Java
MS Excel
iOS
HTML
CSS
Android
Python
C Programming
C++
C#
MongoDB
MySQL
Javascript
PHP
Physics
Chemistry
Biology
Mathematics
English
Economics
Psychology
Social Studies
Fashion Studies
Legal Studies
- Selected Reading
- UPSC IAS Exams Notes
- Developer's Best Practices
- Questions and Answers
- Effective Resume Writing
- HR Interview Questions
- Computer Glossary
- Who is Who
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
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
- Related Articles
- Get the first element from a Sorted Set in Java
- Get the element ordered last in Java TreeSet
- Retrieve the last element from a LinkedList in Java
- How to remove the last element from a set in Python?
- How to delete last element from a set in C++
- Get the last index of a particular element in an ArrayList in Java
- Get last key from NavigableMap in Java
- Get last entry from NavigableMap in Java
- Creating a Sorted Set in Java
- Golang program to get the first and last element from a slice
- C# program to get the last element from an array
- Delete first and last element from a LinkedList in Java
- Swift Program to Get a Random Element from the Set
- Get the last record from a table in MySQL database with Java?
- Program to get the last element from an array using C#

Advertisements