Java SortedSet Interface Example

SortedSet is a Set that maintains its elements in ascending order, sorted according to the natural ordering or according to a Comparator provided at SortedSet creation time. 

Java SortedSet Interface Example

This example demonstrates the few API of SortedSet Interface using TreeSet implementation class.
import java.util.Comparator;
import java.util.SortedSet;
import java.util.TreeSet;

public class CreateTreeSetExample {
    public static void main(String[] args) {
         // Creating a TreeSet
        SortedSet<String> fruits = new TreeSet<>();

        // Adding new elements to a TreeSet

       // Returns the first (lowest) element currently in this set.
        String first = fruits.first();
        System.out.println("First element : " + first);

        // Returns the last (highest) element currently in this set.
        String last = fruits.last();
        System.out.println("Last element : " + last);

        // Returns the comparator used to order the elements in this set, or
        // null if this set uses the natural ordering of its elements.
        Comparator<?> comparator = fruits.comparator();

        SortedSet<String> tailSet = fruits.tailSet("Orange");
        System.out.println("tailSet :" + tailSet);
First element : Apple
Last element : Pineapple
tailSet :[Orange, Pineapple]


Free Spring Boot Tutorial - 5 Hours Full Course

Watch this course on YouTube at Spring Boot Tutorial | Fee 5 Hours Full Course