Sunday, April 7, 2013

Java TreeSet Example

Java TreeSet Example

TreeSet is the class which is available in java.util package.

The main advantage of TreeSet is, it automatically sorts the elements.

TreeSet implements the Set interface, it doesn't allow the Null values and allows unique elements.

TreeSet has lot of methods which are very much useful.

TreeSet isEmpty() method which checks whether the TreeSet is empty or not.

TreeSet methods are remove,removeall, add,addall,contails,contailsall...etc

 Java TreeSet Example Code


import java.util.Iterator;
import java.util.TreeSet;
//TreeSet Example Java
public class TreeSetExampleJava {

    public static void main(String[] args) {
        //TreeSet, it sorts the elements.
        TreeSet<String> treeSet = new TreeSet<String>();
        treeSet.add("corejava");
        treeSet.add("jsp");
        treeSet.add("jsp");
        //treeSet.add(null);
        treeSet.add("servlets");
        treeSet.add("jdbc");
        
        Iterator<String> iterator = treeSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        treeSet.remove("jsp");
        System.out.println("After removing jsp");
        // after removing jsp
        iterator = treeSet.iterator();
        while (iterator.hasNext()) {
            System.out.println(iterator.next());
        }
        if (treeSet.contains("jdbc")) {
            System.out.println("jdbc available");
        }

    }

}


Output :
 
corejava
jdbc
jsp
servlets
After removing jsp
corejava
jdbc
servlets
jdbc available


1 comment :

 
Disclaimer : If you find any mistakes / corrections / feedback Please let us know...This website author shall not accept liability or responsibility for any errors, mistakes or misstatements found in this website.