Thursday, October 30, 2014

Java Tree Pro



Get Tail Set from Java Tree Set

import java.util.SortedSet;
import java.util.TreeSet;
public class GetTailSetFromTreeSetExample
{
public static void main(String[] args)
{
TreeSet tSet = new TreeSet();
tSet.add("1");
tSet.add("3");
tSet.add("2");
tSet.add("5");
tSet.add("4");
SortedSet sortedSet = tSet.tailSet("2");
System.out.println("Tail Set Contains : " + sortedSet);
   }
}

Get lowest and highest value stored in Java Tree Set

import java.util.TreeSet;
public class GetLowestHighestValueTreeSetExample
{
public static void main(String[] args)
{
TreeSet tSet = new TreeSet();
tSet.add("1");
tSet.add("3");
tSet.add("2");
tSet.add("5");
tSet.add("4");
System.out.println("Lowest value Stored in Java TreeSet is : " + tSet.first());
System.out.println("Highest value Stored in Java TreeSet is : " + tSet.last());
   }
}

Iterate through elements of Java Tree Set

import java.util.TreeSet;
import java.util.Iterator;
public class IterateThroughElementsOfTreeSetExample
{
public static void main(String[] args)
{
TreeSet tSet = new TreeSet();
tSet.add(new Integer("1"));
tSet.add(new Integer("2"));
tSet.add(new Integer("3"));
Iterator itr = tSet.iterator();     
System.out.println("TreeSet contains : ");
while(itr.hasNext())
System.out.println(itr.next());
   }
}

Remove all elements from Java Tree Set

import java.util.TreeSet;
public class RemoveAllElementsFromTreeSetExample
{
 public static void main(String[] args)
{
TreeSet tSet = new TreeSet();
tSet.add(new Integer("1"));
tSet.add(new Integer("2"));
tSet.add(new Integer("3"));
System.out.println("TreeSet before removal : " + tSet);
tSet.clear();
System.out.println("TreeSet after removal : " + tSet);
System.out.println("Is TreeSet empty ? " + tSet.isEmpty());    
   }
}

Remove specified element from Java Tree Set

import java.util.TreeSet; 
public class RemoveSpecifiedElementFromTreeSetExample
 {
public static void main(String[] args)
{
TreeSet tSet = new TreeSet();
tSet.add(new Integer("1"));
tSet.add(new Integer("2"));
tSet.add(new Integer("3"));
System.out.println("TreeSet before removal : " + tSet);
boolean blnRemoved = tSet.remove(new Integer("2"));
System.out.println("Was 2 removed from TreeSet ? " + blnRemoved);     
System.out.println("TreeSet after removal : " + tSet);
   }
}

Simple Java Tree Set

import java.util.TreeSet;; 
public class SimpleJavaTreeSetExample
{
public static void main(String[] args)
{
TreeSet tSet = new TreeSet();
tSet.add(new Integer("1"));
tSet.add(new Integer("2"));
tSet.add(new Integer("3"));
System.out.println("TreeSet contains.." + tSet);  
    }
}

No comments:

Post a Comment