Java SortedSet interface

Introduction

The SortedSet interface, which extends Set, maintain their elements in sorted order.

The order can be the elements' natural order or an order specified by a Comparator.

Class TreeSet implements SortedSet.


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

public class Main {
  public static void main(String[] args) {
    // create TreeSet from array colors
    String[] colors = { "CSS", "Java", "C", "C++", "SQL", "Javascript", "Python", "CSS3", "HTML" };
    SortedSet<String> tree = new TreeSet<>(Arrays.asList(colors));

    System.out.println("full:");
    printSet(tree);//from w ww  .  j  a  v  a 2 s.c  o m

    System.out.println("head:");
    printSet(tree.headSet("Java"));

    System.out.println("tail:");
    printSet(tree.tailSet("Java"));

    System.out.printf("first: %s%n", tree.first());
    System.out.printf("last : %s%n", tree.last());
  }

  // output SortedSet using enhanced for statement
  private static void printSet(SortedSet<String> set) {
    for (String s : set)
      System.out.println(s);
    
    System.out.println();
  }
}



PreviousNext

Related