TreeSet last() Method in Java
The Java.util.TreeSet.last() method is used to return the last of the element of a TreeSet. The last element here is being referred to the highest of the elements in the set. If the elements are of integer types, then the largest integer is returned. If the elements are of the string types, then the elements are checked in the alphabetical order and the string starting with the last alphabets in the order of dictionary is returned irrespective of length.
Attention reader! Don’t stop learning now. Get hold of all the important Java Foundation and Collections concepts with the Fundamentals of Java and Java Collections Course at a student-friendly price and become industry ready. To complete your preparation from learning a language to DS Algo and many more, please refer Complete Interview Preparation Course.
Parameters: The method does not take any parameters.
Return Value: The method returns the highest member of the set. If the elements are of string type then they are checked in alphabetical order irrespective of length and if the elements are of integer types then the largest integer is returned. The string of alphabet types is given higher priority.
Below are the programs illustrating the use of Java.util.TreeSet.last() method:
Program 1: When the elements are of integer types:
TreeSet: [7, 8, 14, 48, 124, 200] The last element is: 200
Program 2: When the elements are of string types:
TreeSet: [Ab, B, Geeks, To, TreeSet, Welcome] The last element is: Welcome
Program 3: When the elements are of string types but with integer values. Here we see that the alphabets appearing to the last in the dictionary are given higher priority:
TreeSet: [45, 90000000, Geeks, To, Welcome, Z] The last element is: Z