TreeSet In java

In the last tutorial we learnt LinkedList and HashSet , TreeSet is similar Hashset , except.
Treeset sort the elements in ascending order and allow null element
Hashset doesn't maintain any orders  and doesn't not allow null and both no duplicate values.

import java.util.TreeSet;

public class Example1 {
 public static void main(String args[]) {
        // TreeSet of String Type
TreeSet<String> treeSet = getBookTreeSet();
TreeSet<Integer> treeNum = getTreeSetNum();
  }
  public static TreeSet<String> getBookTreeSet(){
  TreeSet<String> treeSet = new TreeSet<String>();

        // Adding elements to TreeSet<String>
  System.out.println("TreeSet of Book");
        treeSet.add("Book1");
        treeSet.add("Book1");
        treeSet.add("Book2");
        treeSet.add("Book2");
        treeSet.add("Ink");
        treeSet.add("Ink");
        treeSet.add("Cat");
        treeSet.add("null");
        //Displaying TreeSet
        System.out.println(treeSet);
     
        return treeSet;
  }
  public static TreeSet<Integer> getTreeSetNum(){
  // TreeSet of Integer Type
        TreeSet<Integer> treeSet2 = new TreeSet<Integer>();
        System.out.println("TreeSet of number");
        // Adding elements to TreeSet<Integer>
        treeSet2.add(88);
        treeSet2.add(88);
        treeSet2.add(7);
        treeSet2.add(101);
        treeSet2.add(101);
        treeSet2.add(101);
        treeSet2.add(222);
        System.out.println(treeSet2);
        return treeSet2;
  }
}
//result : 

TreeSet of Book
[Book1, Book2, Cat, Ink, null]
TreeSet of number
[7, 88, 101, 222]

we saw the result Treeset sorted and allow null as well as no duplicate values


EmoticonEmoticon