java util TreeSet Class - java.util.TreeSet Class in Java
java.util.TreeSet Class
TreeSet Class in Java
The TreeSet class works exactly the same as the HashSet class with one notable exception: instead of keeping its elements unordered, a TreeSet keeps its elements ordered internally. Not only all the elements ordered, but the tree is balanced. More specifically, it's a red−black tree. Having a balanced tree guarantees a quick o(log n) search time at the cost of a more time−intensive insertion (and deletion). Of course, elements added to the tree must be orderable.
A NavigableSet implementation based on a TreeMap. The elements are ordered using their natural ordering, or by a Comparator provided at set creation time, depending on which constructor is used.
Because TreeSet implements the SortedSet interface as well as the Set interface, understanding TreeSet is a little more involved than HashSet.
How TreeSet Works Internally in Java ?
Java TreeSet class is part of Java’s collections framework. It implements the NavigableSet interface, which in turn extends the SortedSet interface.
The TreeSet class internally uses a TreeMap to store elements. The elements in a TreeSet are sorted according to their natural ordering. You may also provide a custom Comparator to the TreeSet at the time of creation to let it sort the elements based on the supplied comparator.
TreeSet keeps its elements ordered internally. Not only all the elements ordered, but the tree is balanced.
How TreeSet Sort Elements Internally in Java ?
TreeSet keeps its elements sort (ordered) internally. Not only all the elements sort (ordered), but the tree is balanced.
In order to maintain an ordering, elements added to a tree set must provide some way for the tree to order them. If the elements implement the Comparable interface, the first constructor is sufficient. If, however, the objects aren't comparable or you don't like the default ordering provided, you can pass along a custom Comparator to the constructor that will be used to keep elements ordered. Once the TreeSet is created, you cannot change the comparator.
What are the Red Black Tree Rules in Java ?
- Every node in the tree is either black or red.
- The root is always black.
- If a node is red, its children must be black.
- Every path from the root to a leaf (or null child) must contain the same number of black nodes.
This Java TreeSet tutorial also helpful for the following questions :
- What is a TreeSet ?
- How TreeSet works in java ?
- Internal implementation of TreeSet in java ?
- Java TreeSet complete reference ?
In this tutorial you can learn about java.util.TreeSet class and its examples. And also learn how to use java.util.TreeSet class.
java.util.TreeSet class Example
/* Java TreeSet class Example
Save with file name TreeSetExample.java */
import java.util.TreeSet;
public class TreeSetExample
{
public static void main(String args[])
{
// java.util.TreeSet DECLARATION
TreeSet ts;
// java.util.TreeSet OBJECT CREATION
// USING DEFAULT CONSTRUCTOR
ts = new TreeSet();
// ADD AN ELEMENT
ts.add("Huda Tutorials");
ts.add("Java Tutorials");
// DUPLICATES NOT ALLOWED
ts.add("Huda Tutorials");
ts.add("C Tutorials");
ts.add("CPP Tutorials");
// RETURNS COUNT OF ELEMENTS TreeSet CONTAINS
System.out.println("Elements Count : " + ts.size());
// java.util.TreeSet OUTPUT
System.out.println(ts);
}
}
How to use TreeSet with Iterator
The following example shows how to use TreeSet with Iterator.
/* How to use TreeSet with Iterator Example
Save with file name TreeSetExample2.java */
import java.util.TreeSet;
import java.util.Iterator;
public class TreeSetExample2
{
public static void main(String args[])
{
// java.util.TreeSet DECLARATION
TreeSet ts;
// java.util.TreeSet OBJECT CREATION
// USING DEFAULT CONSTRUCTOR
ts = new TreeSet();
// ADD AN ELEMENT
ts.add("Huda Tutorials");
ts.add("Java Tutorials");
// DUPLICATES NOT ALLOWED
ts.add("Huda Tutorials");
ts.add("C Tutorials");
ts.add("CPP Tutorials");
// RETURNS COUNT OF ELEMENTS TreeSet CONTAINS
System.out.println("Elements Count : " + ts.size());
// java.util.TreeSet OUTPUT
Iterator itr = ts.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
How to use TreeSet with Arrays
The following example shows how to use TreeSet with Arrays, Set and Iterator in descending order.
/* How to use TreeSet with Arrays Example
Save with file name TreeSetExample3.java */
import java.util.TreeSet;
import java.util.Set;
import java.util.Arrays;
import java.util.Iterator;
public class TreeSetExample3
{
public static void main(String args[])
{
String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};
TreeSet ts; // java.util.TreeSet DECLARATION
// java.util.Set OBJECT CREATION USING ARRAY AS LIST
// USING DEFAULT CONSTRUCTOR
ts = new TreeSet(Arrays.asList(elements));
// java.util.TreeSet OUTPUT
Iterator itr = ts.descendingIterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
java.util.TreeSet class Example 4
/* Java TreeSet class Example 4
Save with file name TreeSetExample4.java */
import java.util.TreeSet;
import java.util.Arrays;
import java.util.Iterator;
public class TreeSetExample4
{
public static void main(String args[])
{
String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};
TreeSet s; // java.util.TreeSet DECLARATION
// java.util.TreeSet OBJECT CREATION USING ARRAY AS LIST
s = new TreeSet(Arrays.asList(elements));
// ADD ELEMENT TO Set COLLECTION
s.add("NetBeans Tutorials");
// DISPLAY SIZE OF THE Set COLLECTION
System.out.println("TreeSet Collection Size : "+s.size());
// CHECK THE Set COLLECTION IS EMPTY
System.out.println("TreeSet Collection is Empty : "+s.isEmpty());
// CHECK THE GIVEN ELEMENT IN Set COLLECTION
System.out.println("\"Huda Tutorials\" Contains :"+s.contains("Huda Tutorials"));
// RETURNS FIRST LOWEST ELEMENT
System.out.println("First :"+s.first());
// RETURNS LAST ELEMENT
System.out.println("Last :"+s.last());
// java.util.Set OUTPUT
System.out.println("Elements Before Element Remove");
Iterator itr = s.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
s.remove("C Tutorials");
System.out.println("Elements After Element Remove");
itr = s.iterator();
while(itr.hasNext())
{
System.out.println(itr.next());
}
}
}
how to compare two Set Collections
The following example shows how to compare two Set Collections.
/* how to compare two Set Collections Example
Save with file name TreeSetExample5.java */
import java.util.TreeSet;
import java.util.Set;
import java.util.Arrays;
import java.util.Iterator;
public class TreeSetExample5
{
public static void main(String args[])
{
String elements[] = {"Huda Tutorials","Java Tutorials","C Tutorials"};
String elements2[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"};
// java.util.TreeSet DECLARATION
Set s, s2;
// java.util.Set OBJECT CREATION USING ARRAY AS LIST
// USING DEFAULT CONSTRUCTOR
s = new TreeSet(Arrays.asList(elements));
s2 = new TreeSet(Arrays.asList(elements2));
// COMPARE TWO COLLECTIONS
System.out.println("Equals : " + s2.equals(s));
// CONTAINS COLLECTION IN OTHER COLLECTION
System.out.println("Contains : " + s2.containsAll(s));
}
}
How to save Set Collection into file
The following example shows how to save Set Collection into file.
/* How to save Set Collection into file Example
Save with file name TreeSetExample6.java */
import java.util.TreeSet;
import java.util.Set;
import java.util.Arrays;
import java.io.FileOutputStream;
import java.io.ObjectOutputStream;
public class TreeSetExample6
{
public static void main(String args[])
{
try
{
String elements[] = {"Huda Tutorials","Java Tutorials","Android Tutorials"};
// java.util.TreeSet DECLARATION
Set s;
// java.util.Set OBJECT CREATION USING ARRAY AS LIST
// USING DEFAULT CONSTRUCTOR
s = new TreeSet(Arrays.asList(elements));
// FileOutputStream CREATION
FileOutputStream fos = new FileOutputStream("set.set");
// ObjectOutputStream CREATION
ObjectOutputStream oos = new ObjectOutputStream(fos);
// WRITE Set OBJECT TO ObjectOutputStream
oos.writeObject(s);
// CLOSE THE ObjectOutputStream
oos.close();
System.out.println("Set Collection Saved into File Sucessfully");
}
catch(Exception e)
{
System.out.println("Error Occurred : " + e.getMessage());
}
}
}
How to retrieve Set Collection from file
The following example shows how to retrieve Set Collection from file.
/* How to retrieve Set Collection from file Example
Save with file name TreeSetExample7.java */
import java.util.TreeSet;
import java.util.Set;
import java.util.Arrays;
import java.io.FileInputStream;
import java.io.ObjectInputStream;
public class TreeSetExample7
{
public static void main(String args[])
{
try
{
// java.util.TreeSet DECLARATION
Set s;
// FileInputStream CREATION
FileInputStream fis = new FileInputStream("set.set");
// ObjectInputStream CREATION
ObjectInputStream ois = new ObjectInputStream(fis);
// READ Set OBJECT FROM ObjectInputStream
s = (Set) ois.readObject();
ois.close();
System.out.println(s);
}
catch(Exception e)
{
System.out.println("Error Occurred : " + e.getMessage());
}
}
}
How to create a tree with a Comparator
The following example shows how to create a tree with a Comparator, filling the tree, and getting that comparator.
/* How to create a tree with a Comparator, filling the tree,
and getting that comparator Example
Save with file name TreeSetExample8.java */
import java.util.TreeSet;
import java.util.Collections;
public class TreeSetExample8
{
public static void main(String args[])
{
// java.util.TreeSet DECLARATION
TreeSet ts;
// java.util.TreeSet OBJECT CREATION
// USING DEFAULT CONSTRUCTOR
ts = new TreeSet(Collections.reverseOrder());
// ADD AN ELEMENT
ts.add("Huda Tutorials");
ts.add("Java Tutorials");
ts.add("C Tutorials");
ts.add("CPP Tutorials");
// java.util.TreeSet OUTPUT
System.out.println(ts);
// java.util.TreeSet Comparator
System.out.println(ts.comparator());
}
}