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


2 comments :

  1. Hi there! I simply wish to give you a huge thumbs up for your excellent information you've got here on this post. I am returning to your web site for more soon.
    CLick here for information.

    ReplyDelete

 
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.