Java Collections: TreeSet Example

·         Stores the elements in a balanced binary tree
·         A binary tree is a tree in which each node has at most two children
·         TreeSet elements are ordered
·         Less efficient than HashSet in insertion due to the use of a binary tree
·         Its methods are not synchronized
 
image
 

Example

package mycollectiontest;

import java.util.Iterator;
import java.util.Set;
import java.util.TreeSet;

public class CollectionExample {

public static void main(String[] args) {
Set<String> tset = new TreeSet<String>();

// Adding objects
tset.add("Java");
tset.add("PHP");
tset.add("Jboss");
tset.add(".Net");
tset.add("Oracle");

System.out.println("treeset values = " + tset);

Iterator<String> i = tset.iterator();
while (i.hasNext()) {
System.out.println("Elements " + i.next());
}

}

}

Output

treeset values = [.Net, Java, Jboss, Oracle, PHP]
Elements .Net
Elements Java
Elements Jboss
Elements Oracle
Elements PHP

No comments:

Post a Comment

12 classic String-based Java interview questions with simple explanations and code.

  1️⃣ Check if a String is a Palindrome Problem Given a string, check if it reads the same forward and backward. Example: "madam...

Featured Posts