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 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()
Programimport 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