TreeSet Example Java Program
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]
Java Collection Programs
- Linked List Example Java Program
- ArrayList Example Java Program
- HashSet Example Java Program
- Clear an Arraylist Example Java Program
- Reversing an ArrayList Example Java Program
- Linked HashSet Example Java Program
- HashMap Example Java Program
- Set Value in ArrayList Example Java Program
- Linked HashMap Example Java Program
- Remove Element from ArrayList Example Java Program
- Identity HashMap Example Java Program
- TreeMap Example Java Program
- TreeSet Example Java Program
- Finding Duplicates in Array Using TreeSet Java Example Program
- HashTable Example Java Program
- EnumSet Example Java Program
- Enum Map Example Java Program
- Wrapper Example Java Program
- Un Modifiable Wrapper Example Java Program
- Iterator Interface Example Java Program
- Sorted Map Interface Example Java Program
- Sorted Set Interface Example Java Program
Read More Articles
- Multiple Inheritance Using Interface Example Java Program
- Single Inheritance Example Java Program
- Multilevel Inheritance Example Java Program
- Hierarchical Inheritance Example Java Program
- Find all Substrings of a given string Example Java Program
- Create Matrix Example Java Program
- Sum Of Three Numbers Example Java Program
- Heap Sort Example Java Program
- Twin Prime Example Java Program
- Compile Time Polymorphism Example Java Program