Image

Java - Core Java - Collection Framework - SortedSet

SortedSet

  • It is a child interface of set.
  • If we want to represent a group of individual objects according to some sorting order without duplication then we should go for SortedSet.
  • TreeSet

  • Underlying Data structure is balanced tree.
  • Duplicates are not allowed.
  • All object will be inserted based on some sorting order, It may be default natural sorting order or Heterogeneous objects are not allowed.
  • Null insertion is possible (only once).
  • TreeSet implements Serializable & cloneable but not RandomAccess.
  • Program
    import java.util.*;
    public class TreeSetDemo {
        public static void main(String[] args) {
            TreeSet ts=new TreeSet();
            ts.add("A");
            ts.add("Z");
            ts.add("D");
            ts.add("C");
            ts.add("B");
            //ts.add(10);   ClassCastException
            //ts.add(null);  NullPointerException  
            System.out.println(ts);
        }    
    }
    O/P
    [A, B, C, D, Z]
    

    NavigableSet (I)

    NavigableSet is a sub interface of the SortedSet Interface, so it inherits all SortedSet’s behaviors like range, view, endpoints and comparator access. In addition, the NavigableSet interface provides navigation methods and descending iterator that allows the elements in the set can be traversed in descending order.

    The NavigableSet interface overloads the following methods from SortedSet.

    headSet() subSet() tailSet()

    Program
     import java.util.*;
    public class NavigableSetDemo {
        public static void main(String[] args) {
            NavigableSet setFruits=new TreeSet<>();
            setFruits.addAll(Arrays.asList("Banana","Apple","Orange","Grape","Mango"));
            System.out.println("Set Fruits: "+setFruits);
            
            Iterator descIterator=setFruits.descendingIterator();
            System.out.println("Fruits by descending order: ");        
            while (descIterator.hasNext()) {
                String next = descIterator.next();
                System.out.println(next);
            }
        }
    }
    O/P
    Set Fruits: [Apple, Banana, Grape, Mango, Orange]
    Fruits by descending order: 
    Orange
    Mango
    Grape
    Banana
    Apple