You can use the first() and last() methods of TreeSet to get the elements at the ends of the tree:
public Object first()
public Object last()
The first() element is the one that is ordered first in the set, while last() is last.
A NoSuchElementException will be thrown by either method if there are no elements in the set.
import java.util.Arrays;
import java.util.Set;
import java.util.TreeSet;
public class MainClass {
public static void main(String args[]) throws Exception {
String elements[] = { "A", "C", "D", "G", "F" };
TreeSet set = new TreeSet(Arrays.asList(elements));
System.out.println(set);
System.out.println(set.first());
System.out.println(set.last());
}
}
[A, C, D, F, G]
A
G