Create TreeSet in Java Example

<__
This Java example shows how to create a simpleTreeSetin Java with an example. This example also performs the following operations onTreeSet:
  1. Add elements to TreeSet usingadd() method
  2. Get the first element from TreeSet usingfirst() method
  3. Get last element from TreeSet usinglast() method

Create TreeSet in Java Example

packagecom.javaguides.collections.treesetexamples;importjava.util.Comparator;importjava.util.SortedSet;importjava.util.TreeSet;publicclassCreateTreeSetExample {publicstaticvoidmain(String[]args) {// Creating a TreeSetSortedSet<String> fruits=newTreeSet<>();// Adding new elements to a TreeSet  fruits.add("Banana");  fruits.add("Apple");  fruits.add("Pineapple");  fruits.add("Orange");// Returns the first (lowest) element currently in this set.String first= fruits.first();System.out.println("First element :"+ first);// Returns the last (highest) element currently in this set.String last= fruits.last();System.out.println("Last element :"+ last);// Returns the comparator used to order the elements in this set, or// null if this set uses the natural ordering of its elements.Comparator<?> comparator= fruits.comparator();SortedSet<String> tailSet= fruits.tailSet("Orange");System.out.println("tailSet :"+ tailSet); }}

Output

First element : AppleLast element : PineappletailSet :[Orange, Pineapple]



Comments