The Collection Framework provides a special Set interface for maintaining elements in a sorted order called SortedSet. A SortedSet is a 
Elements of Set are sorted according to the elements' natural ordering or according to a Comparator provided at SortedSet Creation time.
Methods of SortedSet can throw a NoSuchElementException when no items are contained in the invoking set and ClassCastException is thrown when an object is incompatible with the elements in a set.
Set that maintains its elements in ascending order. SortedSet interface extends Set and declares the behavior of a set sorted in ascending order.Elements of Set are sorted according to the elements' natural ordering or according to a Comparator provided at SortedSet Creation time.
Methods of SortedSet can throw a NoSuchElementException when no items are contained in the invoking set and ClassCastException is thrown when an object is incompatible with the elements in a set.
A NullPointerException is thrown if an attempt is made to use a null object and null is not allowed in the set.
Following is the SortedSet Interface:public interface SortedSet<E> extends Set<E> {
    // Range-view
    SortedSet<E> subSet(E fromElement, E toElement);
    SortedSet<E> headSet(E toElement);
    SortedSet<E> tailSet(E fromElement);
    // Endpoints
    E first();
    E last();
    // Comparator access
    Comparator<? super E> comparator();
}
In addition to those methods defined by Set, the SortedSet interface declares the methods summarized below:
Example:
package com.sample.javase.testing;
import java.util.Iterator;
import java.util.SortedSet;
import java.util.TreeSet;
public class SortedSetInterfaceExample {
 /**
  * @param args
  */
 public static void main(String[] args) {
  /**
   * Sorted set maintains the ascending order for sorting .
   */
  SortedSet<Long> sortedSet = new TreeSet<Long>();
  sortedSet.add(76L);
  sortedSet.add(66L);
  sortedSet.add(796L);
  sortedSet.add(376L);
  System.out.println(sortedSet);
  System.out.println("first element is " + sortedSet.first());//to pring first element
  System.out.println("last element is " +  sortedSet.last());//to pring last element
  for (Iterator<Long> iterator2 = sortedSet.iterator(); iterator2
    .hasNext();) {
   Long long1 = (Long) iterator2.next();
   System.out.println(long1);
  }
 }
}

Nice Tutorial.....
ReplyDeleteThank You Krishna.
Delete