Treeset Example in Java
On this page (10sections)
Introduction
TreeSet is a classic Java console program that demonstrates the concept with complete source code and sample output. The Collections Framework provides ArrayList, HashMap, HashSet and related data structures.
This tutorial walks through the program line by line, explains how the logic works, and highlights best practices you can apply in your own code.
Definition
TreeSet uses a red-black tree implemented by a java.util.TreeMap. The red-black tree makes sure that there are no duplicates. Additionally, it allows TreeSet to implement java.util.SortedSet. Thus TreeSet itself sorts the values in it.
Syntax
TreeSet<variable-type> variableName = new TreeSet<variable-type>();
TreeSet Example Program
import java.util.Scanner;
import java.util.TreeSet;
public class TreeSetExample {
public static void main(String[] args) {
TreeSet<String> treeSet = new TreeSet<String>();
System.out.println("Enter the input Strings to be added in TreeSet");
Scanner input = new Scanner(System.in);
String s1 = input.nextLine();
String s2 = input.nextLine();
String s3 = input.nextLine();
String s4 = input.nextLine();
treeSet.add(s1);
treeSet.add(s2);
treeSet.add(s3);
treeSet.add(s4);
System.out.println("TreeSet is : " + treeSet);
System.out.println("Check if TreeSet is empty : " + treeSet.isEmpty());
treeSet.remove(s2);
System.out.println("After removing element : " + s2 + " TreeSet is : " + treeSet);
}
}
Sample Output
Enter the input Strings to be added in TreeSet
zoooooo
yoooooo
xoooooo
woooooo
TreeSet is : [woooooo, xoooooo, yoooooo, zoooooo]
Check if TreeSet is empty : false
After removing element : yoooooo TreeSet is : [woooooo, xoooooo, zoooooo]
When to use
Use this treeset example when learning or revising core Java syntax.
How it works
-
Execution begins in the
mainmethod — the JVM calls this method when you run the class. -
import java.util.Scanner;imports a class used later in the program. -
import java.util.TreeSet;imports a class used later in the program. -
TreeSet<String> treeSet = new TreeSet<String>();updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below. -
A
Scannerreads typed input from the keyboard (System.in). -
String s1 = input.nextLine();updates a variable used in the calculation or output. -
A
println/printcall writes text to the console — part of the sample output below.
Best Practices
- Use meaningful variable and class names that describe their purpose.
- Compile and run the program locally — modify values to see how output changes.
- Read compiler errors carefully; they usually point to the exact line to fix.
Common Mistakes
- Copying code without understanding each line — practice by changing one statement at a time.
- Mismatching the public class name and the
.javafilename. - Forgetting semicolons at the end of statements.