what is treeset in java code example
Example 1: TreeSet comparator() method in java
import java.util.TreeSet;
public class TreeSetComparatorMethodExample
{
public static void main(String[] args)
{
TreeSet<Integer> ts = new TreeSet<Integer>();
TreeSet<Integer> comp = new TreeSet<Integer>();
ts.add(5);
ts.add(6);
ts.add(7);
ts.add(8);
ts.add(9);
ts.add(10);
comp = (TreeSet)ts.comparator();
if(comp != null)
{
for(Integer element : comp)
{
System.out.println(element + " ");
}
}
else
{
System.out.println("TreeSet comparator value: " + comp);
System.out.println("Hence it is using natural ordering.");
}
}
}
Example 2: trees in java
package MyPackage;
public class Tree {
static class Node {
int value;
Node left, right;
Node(int value){
this.value = value;
left = null;
right = null;
}
}
public void insert(Node node, int value) {
if (value < node.value) { if (node.left != null) { insert(node.left, value); } else { System.out.println(" Inserted " + value + " to left of " + node.value); node.left = new Node(value); } } else if (value > node.value) {
if (node.right != null) {
insert(node.right, value);
} else {
System.out.println(" Inserted " + value + " to right of "
+ node.value);
node.right = new Node(value);
}
}
}
public void traverseInOrder(Node node) {
if (node != null) {
traverseInOrder(node.left);
System.out.print(" " + node.value);
traverseInOrder(node.right);
}
}
public static void main(String args[])
{
Tree tree = new Tree();
Node root = new Node(5);
System.out.println("Binary Tree Example");
System.out.println("Building tree with root value " + root.value);
tree.insert(root, 2);
tree.insert(root, 4);
tree.insert(root, 8);
tree.insert(root, 6);
tree.insert(root, 7);
tree.insert(root, 3);
tree.insert(root, 9);
System.out.println("Traversing tree in order");
tree.traverseLevelOrder();
}
}
Example 3: java treeset
import java.util.*;
Set<String> movies = new TreeSet<String>();
movies.add(E);
movies.add("The Shining");
movies.add("Dawn of the Dead");
movies.add("Zombieland");
Example 4: what is treeset in java
- TreeSet sorts the order and don't accept null
Example 5: TreeSet size() method in java
import java.util.TreeSet;
public class TreeSetSizeMethodExample
{
public static void main(String[] args)
{
TreeSet<String> ts = new TreeSet<String>();
ts.add("watermelon");
ts.add("apple");
ts.add("banana");
ts.add("grapes");
ts.add("mango");
ts.add("orange");
System.out.println("Given TreeSet: " + ts);
System.out.println("size of TreeSet is: " + ts.size());
}
}