Sorted Set Interface Example Java Program


Definition

Unlike a regular set, the elements in a sorted set are sorted, either by the element's compareTo() method, or a method provided to the constructor of the sorted set. The first and last elements of the sorted set can be retrieved, and subsets can be created via minimum and maximum values, as well as the beginning or ending at the beginning or end of the sorted set. The SortedSet interface is implemented by TreeSet.

Syntax

SortedSet<variable-type> variable-name= new TreeSet<variable-type>();

Sorted Set Interface Example Program

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

public class SortedSetInterfaceExample {

    public static void main(String[] args) {
        SortedSet<String> sortedSet = new TreeSet<String>();
        System.out.println("Enter the input to be added in Sorted Set : ");

        Scanner scanner = new Scanner(System.in);
        String val1 = scanner.nextLine();
        String val2 = scanner.nextLine();
        String val3 = scanner.nextLine();
        String val4 = scanner.nextLine();

        sortedSet.add(val1);
        sortedSet.add(val2);
        sortedSet.add(val3);
        sortedSet.add(val4);

        System.out.println(sortedSet);
    }
}

Sample Output

Enter the input to be added in Sorted Set :
zoooooo
boooooo
noooooo
yoooooo
[boooooo, noooooo, yoooooo, zoooooo]