How do I get the last element of SortedSet?

package org.kodejava.example.util;

import java.util.SortedSet;
import java.util.TreeSet;

public class LastSetElement {
    public static void main(String[] args) {
        SortedSet<String> set = new TreeSet<>();
        set.add("One");
        set.add("Two");
        set.add("Three");
        set.add("Four");
        set.add("Five");

        // SortedSet orders the items it contains. After that we get the last
        // item from the set using last() method. The last item will be "Two".
        String lastElement = set.last();
        System.out.println("lastElement = " + lastElement);
    }
}

How do I get the first element of SortedSet?

package org.kodejava.example.util;

import java.util.TreeSet;
import java.util.SortedSet;

public class FirstSetElement {
    public static void main(String[] args) {
        SortedSet<String> set = new TreeSet<>();
        set.add("One");
        set.add("Two");
        set.add("Three");
        set.add("Four");
        set.add("Five");

        // SortedSet orders the items it contains. After that we get the first
        // item from the set using first() method. The fist item will be "Five".
        String firstElement = set.first();
        System.out.println("firstElement = " + firstElement);
    }
}

How do I sort items in a Set?

The trick to sort a java.util.Set is to use the implementation of a java.util.SortedSet such as the java.util.TreeSet class. The example below shows you the result of using the java.util.TreeSet class, in which the items in it will be sorted based on the element’s natural order.

package org.kodejava.example.util;

import java.util.Set;
import java.util.TreeSet;

public class TreeSetDemo {
    public static void main(String[] args) {
        // The TreeSet class is an implementation of a SortedSet, this means
        // that when your are using the TreeSet to store you data collections
        // you'll get the items ordered base on its elements natural order.
        Set<String> set = new TreeSet<>();

        // In the example below we add some letters to the TreeSet, this mean
        // that the alphabets will be ordered based on the alphabet order
        // which is from A to Z.
        set.add("Z");
        set.add("A");
        set.add("F");
        set.add("B");
        set.add("H");
        set.add("X");
        set.add("N");

        for (String item : set) {
            System.out.print(item + " ");
        }
    }
}

This demo prints:

A B F H N X Z