Thursday, October 30, 2014

Java Tree Set Pro



Check if a particular value exists in Java Tree Set

import java.util.TreeSet;
public class CheckValueOfTreeSetExample
 {
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");
boolean blnExists = tSet.contains("3");
System.out.println("3 exists in TreeSet ? : " + blnExists);
   }
}

Copy all elements of Java Tree Set to an Object Array
import java.util.TreeSet; 
public class CopyElementsOfTreeSetToArrayExample
{
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"));
Object[] objArray = tSet.toArray();
System.out.println("TreeSet elements are copied into an Array.
Now Array Contains..");
for(int index=0; index < objArray.length ; index++)
System.out.println(objArray[index]);
   }
}

Get Head Set from Java Tree Set

import java.util.SortedSet;
import java.util.TreeSet;
public class GetHeadSetFromTreeSetExample
{
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.headSet("3");
System.out.println("Head Set Contains : " + sortedSet);
   }
}

Get Size of Java Tree Set

import java.util.TreeSet;
public class GetSizeOfJavaTreeSetExample
{
public static void main(String[] args)
{
TreeSet tSet = new TreeSet();
System.out.println("Size of TreeSet : " + tSet.size());
tSet.add(new Integer("1"));
tSet.add(new Integer("2"));
tSet.add(new Integer("3"));
System.out.println("Size of TreeSet after addition : " + tSet.size());
tSet.remove(new Integer("1"));
System.out.println("Size of TreeSet after removal : " + tSet.size());
   }
}

Get Sub Set from Java Tree Set

import java.util.TreeSet;
import java.util.SortedSet;  
public class GetSubSetFromTreeSetExample
{
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.subSet("2","5");
System.out.println("SortedSet Contains : " + sortedSet);
   }
}

No comments:

Post a Comment