Java - Collection Framework Sorted Set

Introduction

A sorted set is a set that imposes ordering on its elements.

SortedSet interface represents a sorted set.

The elements in a SortedSet can be sorted in a natural order or using a Comparator.

A SortedSet must know how to sort its elements as they are added.

TreeSet class implements the SortedSet interface in the Collections Framework.

The following code shows how to use SortedSet.

String class implements the Comparable interface.

Demo

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

public class Main {
  public static void main(String[] args) {
    // Create a sorted set of some names
    SortedSet<String> sortedNames = new TreeSet<>();
    sortedNames.add("XML");
    sortedNames.add("Oracle");
    sortedNames.add("Eve");
    sortedNames.add("Json");

    // Print the sorted set of names
    System.out.println(sortedNames);
  }/*  w w w . ja v a  2 s  .  c om*/
}

Result

Related Topics